gpt4 book ai didi

delegates - jQuery 使用委托(delegate)会导致每个元素触发事件 (2 4 8 16 32)

转载 作者:行者123 更新时间:2023-12-01 04:21:35 25 4
gpt4 key购买 nike

所以我写了下面的代码:

   jQuery('#contentWrapper').delegate(".addButton", "click", function(){
addRow(jQuery(this));
});

function addRow(thisButton){

var parent = thisButton.parent();
console.log("parent = ",parent);

var childrenNoEvents = thisButton.parent().children().clone(false);
console.log("childrenClone = ",childrenNoEvents);

var cloneWithoutEvents = thisButton.parent().clone(false);
console.log("parentClone = ",cloneWithoutEvents);

thisButton.parent().append(childrenNoEvents);
};

它对像这样的 DOM 元素进行操作

<div class="whatever">
<span>first element</span><span class="addButton">O</span><span class="deleteButton">X</span>
</div>

当我第一次单击 O(具有 addButton 类的 DOM 元素)时,它可以正常工作,但随后的时间它创建/克隆的元素数量是前一次单击的两倍。我认为这与委托(delegate)处理程序为 DOM 中的许多“.addButton”类调用 addRow 有关,但我不知道如何修复它。

奖励问题:

如何使用闭包创建一个持久变量,每次触发事件时我都可以在 addRow 函数内递增该变量? (或者有更好的方法吗?)

最佳答案

每次执行该函数时,都会将 .whatever 的内容复制回 .whatever 中,从而有效地将它们加倍。尝试使用这种方法:

$('#contentWrapper').on("click", ".addButton", function() { // note that I use the .on() function, as .delegate() is just a wrapper since jQuery 1.7
addRow($(this));
});

function addRow(thisButton){
thisButton.closest('ul').append(thisButton.parent().clone(false));
};

使用这样的 HTML 语法:

<div id="contentWrapper">
<ul class="whatever">
<li>
<span>first element</span>
<span class="addButton">O</span>
<span class="deleteButton">X</span>
</li>
</ul>
</div>

您可以使用这个 JSFiddle 进行测试:http://jsfiddle.net/ZsCCs/

有关 .on() 方法的更多信息:http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html

关于delegates - jQuery 使用委托(delegate)会导致每个元素触发事件 (2 4 8 16 32),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9988852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com