I have written a jQuery plugin which has similar functionality as following:
<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. 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.
Where have I done wrong?
您错过了$div
和$btn
前面的var
,并且偶然创建了全局变量。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.