JS委托动态声明元素的唯一事件(one()) [英] JS delegate unique event (one()) for dynamic declared elements
问题描述
我正在研究js项目. HTML的某些部分是通过JS这样生成的:
I'm working on js-project. Some parts of HTML is generating via JS like this:
html += '<div class="button"><a href="' + url1 + '>' + button_text1 + '</a></div>';
html += '<div class="button"><a href="' + url2 + '>' + button_text2 + '</a></div>';
我想要的是为每个按钮的第一次单击创建侦听器.
What I want is create listener to the first click for each of the buttons.
想法1:由于动态声明,请使用$(.button a).live('click', doSomething)
.可悲的是,没有办法像这样在第一次点击时强制触发.也已弃用.
Idea 1: Use $(.button a).live('click', doSomething)
because of dynamic declaration. Sadly, there's no way to force trigger only on the first click like that. Also deprecated.
想法2:使用$(.button a).one('click', doSomething)
.由于on()
而无法正常工作,可能在DOM准备就绪时无法找到选择器,但仍会呈现($(document).ready(...)
).在此处查看详细信息: https://jqueryhouse.com /jquery-方法为动态添加元素的问题/
Idea 2: Use $(.button a).one('click', doSomething)
. Not working because of on()
might fail to find selector when DOM is ready, but still rendering ($(document).ready(...)
). See details here: https://jqueryhouse.com/jquery-on-method-the-issue-of-dynamically-added-elements/
想法3:使用$(body).one('click', '.button a', doSomething)
,即委托事件,如注明的消息来源所建议.
但是似乎JS的读法不是这里是一个元素数组;为每个元素添加one('click')
事件",而是添加Add one('click')
事件以单击数组中的任何元素",因为事件是无论我单击了什么按钮,都只会触发一次.
Idea 3: Use $(body).one('click', '.button a', doSomething)
, i.e. delegate event as noted source suggests.
But it seems like JS is read it not as "Here is an array of elements; for each element add one('click')
event", but as "Add one('click')
event for click on any element from an array", because an event is triggered only once no matter what button I have clicked.
我真的在试图找到如何处理这种情况的任何线索,但是没有运气.我将非常感谢您提供帮助或其他解决方法!
I was really trying to find any clues to how manage this situation but got no luck. I will be really grateful for help or another idea how to solve this!
推荐答案
«我想要为每个按钮的第一次点击创建监听器.»
此处的关键字是每个.
尝试:
$(.button a).each(function(){
$(this).one('click', doSomething); // (!)No prenthesis here... Just the function name.
});
.each()
方法的文档.
Documentation for the .each()
method.
由于您动态地添加了新元素...将html
附加到了容器之后,对它们运行类似的每个循环,如下所示:
Since you append new elements dynamically... After you appended html
to a container, run a similar each loop on them like this:
// Assuming you do this
$(".container_selector").append(html);
// Then run the each loop
$(".container_selector").find(".button a").each(function(){
$(this).one('click', doSomething); // (!)No prenthesis here... Just the function name.
});
这篇关于JS委托动态声明元素的唯一事件(one())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!