假设我需要在 attribute 中编写一个 onclick 处理程序,如下所示:
<a href='#' onclick='DoSomething(); event.stopPropagation(); return false;'>
...</a>
我知道这是不好的形式,但暂时假设我必须使用一个属性。
很遗憾 event
没有定义。我试过 e
也没有定义。有什么方法可以访问属性内的事件对象,或者有什么其他方法可以停止事件传播吗?
最佳答案
获取事件对象的位置取决于浏览器。一些(所有?)IE 版本将它放在 window.event
中,但其他所有人都将它作为参数传递。所以,你最终不得不像这样跳一段愚蠢的小舞:
function DoSomething(event) {
event = event || window.event;
event.stopPropagation();
// Do useful work.
return false;
}
然后像这样设置onclick
:
<a href="javascript:void(0)" onclick="DoSomething(event)">
我还切换到 javascript:void(0)
,这样您就不会遇到常见的“#
interpreted as an in-page fragment”问题。
关于javascript - 有没有办法访问 onclick 属性中的 JavaScript 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975758/