2010-05-13 126 views
1

我试图用json数据填充选择从web服务。我收到错误'对象不支持此属性或方法'。当我这样做$(this).html(options.join('')); 任何想法我做错了什么?jQuery插件问题 - 使用JSON数据填充选择选项

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

当你做了alert(this);'在这行之前,你会得到什么? – 2010-05-13 23:57:51

回答

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

是的,你是绝对正确的'这'指的是jQuery对象本身。谢谢你的帮助。 – dm80 2010-05-14 16:14:57

+0

@ user331884 - 如果您找到有用的答案,请将其投票并点击左侧的链接进行接受 – nickf 2010-05-16 23:52:05