2010-05-13 124 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