通过事件冒泡在 Anchor 内跨度
我有这样的一段 html:
<li class="addToFriends"><a href="....">Something something<span>INSIDE SPAN</span>something</a></li>
要在单击锚点时处理 AJAX 请求,我已经注册了单击事件的处理程序:
$('.addToFriends a').click(function(event){
var target = $(event.target);
if (target.is('a')) {
// if I click on SPAN element following fragment won't execute!
// do ajax request
}
event.preventDefault();
});
我的问题是:
- 为什么为 span 元素引发单击事件? 毕竟,除了上一个问题之外,我没有将单击事件绑定到 SPAN 元素
- ,我认为如果我不处理 SPAN 单击事件,浏览器将使用事件冒泡来引发锚点的单击事件(如果我不调用event.stopPropagation())。 但我也没有解决我的问题,因为点击事件只引发一次
所以现在,我解决了这个问题,我的解决方案是:
$('.addToFriends a').click(function(event){
var target = $(event.target);
if (!target.is('a')) {
target = target.parent('a')
}
...
});
但是,我仍然很好奇为什么它会这样工作......
谢谢,
Paweł
I have such a piece of html:
<li class="addToFriends"><a href="....">Something something<span>INSIDE SPAN</span>something</a></li>
To handle AJAX request when clicking on anchor I have registered handler on click event:
$('.addToFriends a').click(function(event){
var target = $(event.target);
if (target.is('a')) {
// if I click on SPAN element following fragment won't execute!
// do ajax request
}
event.preventDefault();
});
My questions are:
- why click event is raised for span element? After all, I didn't bind click event to SPAN elements
- apart from previous question, I thought that if I won't handle SPAN click event, browser will use event-bubbling to raise click event for anchor (if I won't call event.stopPropagation()). But I also didn't work out for me as that click event is raised only once
So now, I got round that problem I my solution is:
$('.addToFriends a').click(function(event){
var target = $(event.target);
if (!target.is('a')) {
target = target.parent('a')
}
...
});
But still, I'm curious why it works like this...
Thanks,
Paweł
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须使用事件的 currentTarget。
You have to use the currentTarget of your event.
好的,但是如果我单击 SPAN 并调用 stopPropagation() 方法,那么该形式的代码将无法工作:
});
不过,我认为我遗漏了一些与事件冒泡相关的关键点。
Ok, but if I click on SPAN and call stopPropagation() method my code in that form won't work:
});
Still, I thing I'm missing some crucial points related with event bubbling.
您可以随时阅读规范。 此处还提供了一个不错的教程。
仅当您为 SPAN 和 A 元素定义了单击事件处理程序时,StopPropagation 才有意义。 在 SPAN 事件处理程序中调用 stopPropagation 将阻止调用 A 处理程序。 这假定了默认的气泡阶段。
You can always read the specification. A nice tutorial is also available here.
StopPropagation has only meaning if you have defined click event handlers for both the SPAN and A elements. Calling the stopPropagation in the SPAN event handler will prevent the A handler from being called. This assumes the default bubble phase.