获取 jQuery 单击、上下文(this)以输出单个对象,而不是多个
所以我这样做:
$('.divs').bind('click', function()
{
console.log("clicked " +$(this).text());
}
On:
<DIV class="divs" id="parent1">Dad
<DIV class="divs" id="child1">Kid1</DIV>
<DIV class="divs" id="child2">Kid2</DIV>
</DIV>
然后,当我单击 child1 时,我会得到多个输出,例如:
“clicked Kid1”
“clicked DadKid1Kid2”
控制台上的
只有当我单击“最父级”div 时,我才会得到单个输出。 这一切都很合乎逻辑,但我只想选择“最孩子气”的那个?
So I do:
$('.divs').bind('click', function()
{
console.log("clicked " +$(this).text());
}
On:
<DIV class="divs" id="parent1">Dad
<DIV class="divs" id="child1">Kid1</DIV>
<DIV class="divs" id="child2">Kid2</DIV>
</DIV>
Then I get multiple outputs when I click on child1, like:
"clicked Kid1"
"clicked DadKid1Kid2"
on my console
Only when I click on the 'most parent' div i get a single output.
This is all pretty logical, but I'd like to only select the 'most child'-ish one only?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
event.stopPropagation
停止点击事件的传播。请注意,我添加了
event
作为事件处理程序匿名函数的参数。当您单击一个元素时,它会触发一个单击事件,然后该事件将 DOM 一直冒泡到
document
元素,从而触发从原始目标到的每个祖先元素上的单击事件文档
元素。但是我们可以停止此事件传播。您还可以
返回 false;
,这在 jQuery 事件处理程序中将event.preventDefault()
和event.stopPropagation()
。给你的一些文档:
event.stopPropagation()
: http://api.jquery .com/event.stoppropagationevent.preventDefault()
: http://api.jquery.com/event.preventdefault这是一个演示: http://jsfiddle.net/P5tXP/
Stop the propagation of the click event by using
event.stopPropagation
.Notice I added
event
as an argument for the event handler anonymous function.When you click an element it fires a click event, then that event bubbles up the DOM all the way to the
document
element, triggering a click event on each ancestor element from the original target to thedocument
element. We can stop this event propagation however.You can also
return false;
which in a jQuery Event Handler willevent.preventDefault()
andevent.stopPropagation()
.Some documentation for ya:
event.stopPropagation()
: http://api.jquery.com/event.stoppropagationevent.preventDefault()
: http://api.jquery.com/event.preventdefaultHere is a demo: http://jsfiddle.net/P5tXP/
你可以浏览这个网站
javascript go 中的http://www.quirksmode.org/js/events_order.html
事件通过 3 个阶段捕获、目标和冒泡..
如果您只想处理目标
你可以做这样的事情
you can go through this site
http://www.quirksmode.org/js/events_order.html
events in javascript go through 3 phases capturing,at target and bubbling..
if you want to handle only at at target
you can do something like this