如何使用 jquery 跳过冒泡阶段
尝试做一些管理后端的事情,
我有一个包含操作链接的 tr 行。
<tr>
<td>
<span>item1</span>
</td>
<td>
<a href="#">delete</a>
</td>
</tr>
当用户单击 tr 行时,应该选择它(并且处理程序绑定到该事件,因此我可以显示额外的信息 其他地方), 和 当用户单击删除链接时,应调用另一个处理程序来删除该项目。
为两个目标设置单击事件,如下所示:
$("tr").click(function(e){
// show line infos, by reloading the page
});
$("tr a").click(function(e){
// delete item
});
当我单击删除链接时, 看来 tr 事件总是首先被调用, 由于我的 tr 处理程序重新加载页面 链接的处理程序永远不会被调用。 这是正常的,因为冒泡系统会调用 我的处理程序按此顺序:
向下阶段:tr
向上阶段:a tr
如何在向下阶段跳过第一个 tr 的处理程序?
我尝试了一些事情 e.preventDefault()、e.stopPropagation() 没有成功。
Trying to do some administration backend things,
I have a tr line containing action links.
<tr>
<td>
<span>item1</span>
</td>
<td>
<a href="#">delete</a>
</td>
</tr>
When a user clicks on the tr line, it should select it (and a handler is bound to that event, so I can display extra informations
somewhere else),
AND
when a user clicks on the delete link, another handler should be called to delete the item.
Setting the click event for both targets, like this :
$("tr").click(function(e){
// show line infos, by reloading the page
});
$("tr a").click(function(e){
// delete item
});
When I click on the delete link,
it appears that the tr event is always called first,
and since my tr's handler reload the page
the link's handler is never called.
that's normal because bubbling system will call
my handlers in this order :
down phase : tr a
up phase : a tr
How can I skip the first tr's handler in down phase ?
I tried a few things with
e.preventDefault(), e.stopPropagation() without success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的观察似乎有点奇怪。
应首先触发其点击事件,然后是
。如果是这样,事件确实会冒泡,您可以通过停止传播(或返回 false,这将取消默认事件并停止传播)来覆盖冒泡:
工作示例: http://jsfiddle.net/cFjmc/
Your observations seem a little strange. The
<a>
should fire it's click event first, and then the<tr>
. If so, the event will indeed bubble, and you can override the bubbling by stopping propagation (or returning false, which will cancel the default event and stop propagation):Working example: http://jsfiddle.net/cFjmc/
使用 event.stopImmediatePropagation
演示-
use event.stopImmediatePropagation
demo-
是的,你们都是权利,我犯了一个错误,
很抱歉这个奇怪的帖子,
我刚刚意识到我的测试用例不是我提交的测试用例。
现在我可以按正确的顺序处理事情了。谢谢。
yes you all are rights, I made a mistake,
sorry for the strange post,
I just realized that my test case was not the one that I have submitted.
Now I can get things in the right order. Thanks.