jQuery插件问题 - 使用JSON数据填充选择选项

时间:2010-05-13 23:47:10

标签: jquery json input plugins

我正在尝试使用来自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);

1 个答案:

答案 0 :(得分:3)

问题是变量this。在您正在使用的上下文中,this可能是指jQuery对象本身(即不是结果集)。试试这个:

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

    $.getJSON( ... blah blah,

        $t.html(options.join(''));
    )
}
相关问题