[英]jQuery plugin event binding on dynamic element
I have written a jQuery plugin which has similar functionality as following: 我写了一个jQuery插件,它具有以下类似功能:
<h1 id="t1">title 1</h1>
<h1 id="t2">title 2</h2>
<script>
$.fn.extend({
test: function(opts){
var o = { text : 'hello '};
o = $.extend( o, opts );
return this.each(function(){
var $this = $(this);
$div = $('<div/>');
$btn = $('<button />').text(o.text);
$btn.click(function(){
$div.text(o.text);
});
$this.after($btn).after($div);
});
}
});
$('#t1').test({text:'hola '});
$('#t2').test({text:'nihao '});
</script>
in which I have created some elements (a button and a div) on the fly and added some event bindings. 在其中我动态创建了一些元素(一个按钮和一个div)并添加了一些事件绑定。 In the sample code I have more than one element that will use this plugin respectively.
在示例代码中,我有多个元素将分别使用此插件。 However I noticed when I trigger the event, my bound event also applies changes to the last div I have created in the plugin.
但是,当我触发事件时,我注意到,绑定事件还将更改应用于我在插件中创建的最后一个div。
Where have I done wrong? 我在哪里做错了?
您错过了$div
和$btn
前面的var
,并且偶然创建了全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.