限制javascript中的事件传播 [英] restrict event propagation in javascript

查看:104
本文介绍了限制javascript中的事件传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如:

 < tr id =my_tronclick =javascript:my_tr_click();> 
< td>
< a id =my_ataghref =javascript:void(0);的onclick = JavaScript的:my_a_click(); >删除< / A>
< td>
< / tr>

当我点击删除锚标签时,首先是 my_a_click()函数被调用,然后父控件tr onclick函数 - my_tr_click()被调用。我相信这被称为事件传播。



当我点击孩子时,我如何阻止这个 my_tr_click()函数被调用锚定标签?



请帮助我..



谢谢

解决方案

怪癖模式而且这个回答这是很可能你想要处理你的内联 onclick()

  function my_a_click(e){
e.cancelBubble = true;
if(e.stopPropagation)e.stopPropagation();
}

并调整您的标记:

 < a id =my_ataghref =javascript:void(0); onclick =var event = arguments [0] || window.event; my_a_click(event);> Delete< / a> 

在jsfiddle上的工作示例



在chrome,firefox 4和IE9中进行测试。 b
$ b

所有这一切都说,如果jQuery是一个选项,它会使事情更容易。

  $(#my_atag)。click(function(e){
e.stopPropagation();
});

 < a id =my_ataghref =javascript:void(0);> Delete< / a> 


How can I prevent an event from bubbling up to parent in 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. 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?

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().

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

tested in chrome, firefox 4 and IE9.

With all that being said, if jQuery is an option it would make things a lot easier.

$("#my_atag").click(function(e){
  e.stopPropagation();
});

and

<a id="my_atag" href="javascript:void(0);">Delete</a>

这篇关于限制javascript中的事件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆