这是我第一次创建插件。但是我的插件有一些小问题。我在下面创建了我的插件的简单副本
$.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
当我启动单个实例时,我的插件工作正常,但是当我尝试创建多个实例时,只有最后一个实例在工作。
我认为发生这种情况是因为您在不使用var
的情况下声明了element
.
这样,您将element
声明为全局变量,因此element = $(this);
与window.element = $(this);
基本相同。因此,第二个函数调用将覆盖element
的第一个实例。
这应该是一个简单的修复:var element = $(this);