jQuery插件的问题 - 填充JSON数据选择选项(jQuery plugin question

2019-10-21 18:44发布

我试图从web服务填充JSON数据选择。 我收到错误“对象不支持此属性或方法。” 当我这样做$(this).html(options.join('')); 任何想法,我做错了什么?

;(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);

Answer 1:

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(''));
    )
}


文章来源: jQuery plugin question - populate select options with JSON data