2017-07-05 112 views
0

這是我第一次創建插件。但是我的插件有一些小問題。我創建了我的插件簡單翻版低於用ajax創建jquery插件

$.fn.myPlugin = function(url){ 
    return this.each(function() { 
     element = $(this); 
     $.getJSON(url, function(response){ 
      elem.val(response.init_value); 
     }); 
    }); 
} 

,並開始喜歡這個

$("#test1").myPlugin('/get1.json'); //this should value 1 
$("#test2").myPlugin('/get2.json'); //this should value 2 

,但如預期的結果是不工作

Element #test1 has done nothing, no value (I think it is broken) 
Element #test2 has value of 2 

我的插件工作正常,當我啓動一個單一的實例,但當我試圖做出多個實例時,只有最後一個實例正在工作。

回答

1

我認爲這是因爲您聲明element而未使用var

這樣你宣佈element作爲一個全局變量,所以element = $(this);基本上與window.element = $(this);相同。因此,第二個函數調用將覆蓋第一個實例element

這應該是一個簡單的解決辦法:var element = $(this);

+0

OMG。那是它?謝謝vi5ion!你節省了我的一天。 –