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?