开发者

jQuery plugin question - populate select options with JSON data

开发者 https://www.devze.com 2022-12-30 01:12 出处:网络
I\'m trying to fill selects with json data f开发者_如何学JAVArom a web service.I\'m getting error \'Object doesn\'t support this property or method.\'when I do this $(this).html(options.join(\'\'));

I'm trying to fill selects with json data f开发者_如何学JAVArom a web service. I'm getting error 'Object doesn't support this property or method.' when I do this $(this).html(options.join('')); Any ideas what I'm doing wrong?

;(function($) {

    $.fillSelect = {};

    $.fn.fillSelect = function(url, map) {
        var jsonpUrl = url + "?callback=?";        
        $.getJSON(jsonpUrl, function(d) {
           var options = [];
           var txt = map[0];
           var val = map[1];
           options.push('<option>--Select--</option>');
           $.each(d, function(index, item) {
                options.push('<option value="' + item[val] + '">' + item[txt] + '</option>');
           });
           $(this).html(options.join(''));
           //getting error  Object doesn't support this property or method
        };
    };
})(jQuery);


The problem is the variable this. In the context you're using, this is probably referring to the jQuery object itself (that is, not the result set). Try this:

$.fn.fillSelect = function (url, map) {
    var $t = this;     // (this) is the jQuery result set

    $.getJSON( ... blah blah,

        $t.html(options.join(''));
    )
}
0

精彩评论

暂无评论...
验证码 换一张
取 消