[英]jQuery click event lost after appenTo
I am using appendTo to move list items between two list, upon a button click. 我点击按钮,使用appendTo在两个列表之间移动列表项。 The button resides in each
li
element. 按钮位于每个
li
元素中。 Each li
has two buttons, of which only one is visible at a time, depending on the list the li currently resides. 每个
li
有两个按钮,其中一次只能看到一个按钮,具体取决于li当前所在的列表。
Here is the function: 这是功能:
// 'this' is the first list
// Click Handler for remove and add buttons
$(this.selector + ', ' + settings.target + ' li button').click(function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
})
As long as the list item reside in the original li, the click events in the buttons are triggered. 只要列表项位于原始li中,就会触发按钮中的单击事件。 However, once it is moved to the other list using
listItem.apendTo
. 但是,一旦使用
listItem.apendTo
将其移动到其他列表。 The click item no longer fires. 点击项目不再触发。 Why is this the case?
为什么会这样? I cant find anything about this in the docs.
我在文档中找不到任何相关内容。
Sometimes jQuery won't be able to find something if it isn't present in the DOM when your script first loads. 有时,如果脚本首次加载,jQuery不存在,jQuery将无法找到。 If it is a dynamically created element, try replacing your click event handlers with 'on'
如果它是动态创建的元素,请尝试使用“on”替换您的click事件处理程序
Rather than: 而不是:
$(".aClass").click(function(){
// Code here
})
Try: 尝试:
$("body").on("click", ".aClass", function(){
Code here
})
As recommended by user 'apsdehal', a deleate was what i needed: 根据用户'apsdehal'的建议,删除是我需要的:
// Click Handler for remove and add buttons
$(source.selector + ', ' + settings.target ).delegate("li button", "click", function(e) {
var button = $(e.target);
var listItem = button.parent('li');
listItem.children("button").toggleClass("hidden");
if (button.hasClass("assign")) {
// Add Element to assignment list
listItem.appendTo(settings.target);
}
else
if (button.hasClass("remove")) {
// Remove Element from assignment list
listItem.appendTo(source);
}
});
You should use on
event. 你应该使用
on
event。
$(".aClass").on("click", function(){
//Your custom code
})
on
event is usful for Dynamically generated data + static data already in HTML. on
event对于动态生成的数据+ HTML中的静态数据非常有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.