[英]restrict event propagation in javascript
How can I prevent an event from bubbling up to parent in javascript? 如何防止事件在JavaScript中冒泡到父级?
Eg. 例如。
<tr id="my_tr" onclick="javascript:my_tr_click();">
<td>
<a id="my_atag" href="javascript:void(0);" onclick="javascript:my_a_click();">Delete</a>
<td>
</tr>
When I click on "Delete" anchor tag, first the my_a_click() function gets called, and then the parent tr onclick function - my_tr_click() - gets called. 当我单击“删除”锚标记时,首先调用my_a_click()函数,然后调用父tr onclick函数-my_tr_click() -。 This, I believe, is called event propagation. 我认为这称为事件传播。
How can I stop that my_tr_click() function from getting called when I click on the child anchor tag? 当我单击子锚标记时,如何阻止my_tr_click()函数被调用?
Please help me out.. 请帮帮我..
Thanks 谢谢
From quirks mode and also this answer this is most likely what you want to do to handle your inline onclick()
. 从怪癖模式以及此答案中,这很可能是您想要处理内联onclick()
。
function my_a_click(e) {
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
And adjust your markup: 并调整您的标记:
<a id="my_atag" href="javascript:void(0);" onclick="var event = arguments[0] || window.event; my_a_click(event);">Delete</a>
Working example on jsfiddle jsfiddle上的工作示例
tested in chrome, firefox 4 and IE9. 在chrome,firefox 4和IE9中进行了测试。
With all that being said, if jQuery is an option it would make things a lot easier. 所有这样说,如果jQuery是一个选项,它会使事情更容易。
$("#my_atag").click(function(e){
e.stopPropagation();
});
and 和
<a id="my_atag" href="javascript:void(0);">Delete</a>
I think you may be interested in http://www.quirksmode.org/js/introevents.html 我认为您可能对http://www.quirksmode.org/js/introevents.html感兴趣
something.onclick = function (e) {
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.