我的插件有问题,因为我需要一种方法来更新新元素是否添加到DOM中我添加了一个更新方法, 如果我启动插件一切都好那么,一切工作完美,没有问题,没有错误,但一旦我添加一个新的Elelemnt(与类框的div) 的事情出错了,更新的作品,但点击事件似乎现在多次启动,所以如果我添加一个新元素,事件运行两次,如果我将2个元素添加到DOM,事件运行3次....等等。我对Js并不擅长,所以我被困在这里,我尝试了很多,但似乎没有任何工作。将新内容添加到DOM后多次运行的事件
新添加的元素工作正常,但如果我添加一些更多的新元素,他们将有相同的问题。
我在一个小的预览下面添加了一个小插件,因为我的插件是自定义的,我只发布了有问题的部分(使它们易于理解)。
是需要的更新的方法,新的元素(■)需要更新(新的代码添加到.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);
确保您的.click()仅针对较新的元素。不是旧的。鉴于上面的代码,它表明你有重复的ID是无效的,也会导致问题。 –
'.myplugin01('update')'做了什么? –
是的,你的问题驻留在你的'update'方法中,这是你没有发布的方法。 – Nelson