[英]Jquery replaceWith() inside loop with click events
im trying to replace various elements with another inside a jquery .each loop and give them on click events to their child nodes, but it does not work, here is my code. 我试图用jquery .each循环中的另一个替换各种元素,并在它们的子节点上将click事件提供给它们,但这是行不通的,这是我的代码。
var replacer = function () {
var elementbody = "<div class='Container'><div class='Button'></div></div>";
$('.myclass').each(function (index, element) {
$(element).replaceWith(elementBody);
$(element).find('.Button').click(function () {
//------------------To do on click event------------------//
});
};
After you use 使用后
$(element).replaceWith(...);
element
still refers to the old element, not the elements that have replaced it. element
仍然是指旧元素,而不是已替换旧元素的元素。 So $(element).find('.Button')
doesn't find the button you just added. 因此
$(element).find('.Button')
找不到您刚刚添加的按钮。
Instead of adding the handler to each element that you add, use delegation to bind a handler just once, as explained in Event binding on dynamically created elements? 无需将处理程序添加到添加的每个元素,而是使用委托仅绑定一次处理程序,如动态创建的元素的事件绑定中所述?
$("someSelector").on("click", ".Button", function() {
...
});
You can use a delegate as Barmar suggests or you could provide yourself with a new jquery object that references your new content before running the replaceWith
您可以按照Barmar的建议使用委托,也可以在运行
replaceWith
之前为自己提供一个引用新内容的jquery对象。
Something like this, maybe: 可能是这样的:
new_element = $('<div><button>Hello World</button></div');
$(element).replaceWith(new_element);
new_element.find('button').on('click', function(e) {
console.log(e);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.