jQuery document.on()子选择器 [英] jQuery document.on() child selector
问题描述
我有一个ul,我想在点击一个孩子时创建一个提醒。
I have a ul and i want create an alert when i click on a child li.
<ul id="myul">
<div class="test">
<div class="test1">
<li></li>
<li></li>
</div>
</div>
</ul>
这样的事情是可能的:
$(document).on('click', '#myul.find(li)', function()
{
alert('hey!');
}
我不能使用 #myul> li
因为我在 li
之前还有其他孩子。
I can't use #myul > li
because I have other child before li
.
推荐答案
你可以使用
$(document).on('click','#myul li', eventHandler)
这意味着您在文档上注册了一个事件处理程序,但 eventHandler 仅当事件源自
#myul li
时,才会调用code>,即对于任何 li
的子项 myul
,不仅仅是直接的孩子,也可以是适合你情况的后代。
which means you're registering an event handler on the document but eventHandler
will be invoked only when the event originated from #myul li
i.e for any li
child of myul
, not just the immediate child, can be a descendant as well which fits your case.
但我建议您甚至可以将事件注册的范围缩小到 li
的最近祖先,如下所示。
But I suggest that you even reduce the scope of the event registration to the closest ancestor of li
like below.
$('#myul').on('click','li', eventHandler)
这篇关于jQuery document.on()子选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!