向DOM添加新内容后多次运行的事件



我的插件有问题,因为如果向DOM添加新元素,我需要一种更新方法。我添加了一个更新方法,如果我启动插件一切顺利,一切都很完美,没有问题,没有错误,但一旦我添加了一个新的elemnt(带有类框的div)DOM出现问题,更新有效,但点击事件现在似乎触发了多次,所以如果我添加一个新元素,事件就会运行两次,如果我向DOM添加2个元素,事件将运行3次。。。。等等。我不太擅长Js,所以我一直在努力,我尝试了很多,但似乎都不起作用。

新添加的元素可以正常工作,但如果我再添加一些新元素,它们将出现相同的问题。

我在下面添加了一个小预览,因为我的插件是自定义的,所以我只发布了有问题的部分(使它们易于理解)。

需要更新方法,需要更新新元素(.box)(在.box中添加新代码)

HTML代码

<div id="container">
<div class="box">
<a href="#" class="link1">link 1</a>
<a href="#" class="link1">link 2</a>
<div>content goes here...</div>
</div>
<div class="box">
<a href="#" class="link1">link 1</a>
<a href="#" class="link1">link 2</a>
<div>content goes here...</div>
</div>
<div class="box">
<a href="#" class="link1">link 1</a>
<a href="#" class="link1">link 2</a>
<div>content goes here...</div>
</div>
</div>

内联脚本

$('#container').myplugin01();
$('#somelink').click(function(e){
$('#container').append('<div class="box"><a href="#" class="link1">link 1</a><a href="#" class="link1">link 2</a><div>content goes here...</div></div>'); 
$('#container').myplugin01('update');
});

插件

;(function($, window, document, undefined){
//"use strict"; // jshint ;_;
var pluginName = 'myplugin01';
var Plugin = function(element, options){
this.init(element, options);
};
Plugin.prototype = {
init: function(element, options){
this.elm     = $(element);
this.options = $.extend({}, $.fn[pluginName].options, options);

// example 1: animation
$('#container').children('.box').on("click", ".link1", function(e){
$(this).parent().children('div').animate({height: 'toggle'},400)
});
// example 2: wrapping
$('#container').children('.box').on("click", ".link2", function(e){
$(this).parent().wrap('<div class="wrapped"></div>')
});

this.update();
},
update: function(){
$('#container').children('.box').addClass('someclass');
// more code here...
}
};
$.fn[pluginName] = function(option) {
var options = typeof option == "object" && option;
return this.each(function() {
var $this = $(this);
var data  = new Plugin($this, options);
if(!$.data($this, pluginName)){           
$.data($this, pluginName, data);
}
if(typeof option == 'string'){
data[option]();
}
});
};
/**
* Default settings(dont change).
* You can globally override these options
* by using $.fn.pluginName.key = 'value';
**/
$.fn[pluginName].options = {
name: 'world' 
};

})(jQuery, window, document);

如果多次绑定事件,就会出现此问题。

// inline script
$('#container').myplugin01();// binding first time
$('#somelink').click(function(e){
$('#container').append('<div class="box"><a href="#" class="link1">link 1</a><a href="#" class="link1">link 2</a><div>content goes here...</div></div>'); 
$('#container').myplugin01('update');// binding second time
// We suggest you to unbind here and rebind it.
});

最新更新