考虑以下几点:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
我怎么能使它,当用户点击跨度,它不火div的点击事件?
考虑以下几点:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
我怎么能使它,当用户点击跨度,它不火div的点击事件?
当前回答
记住那个窗口。事件在FireFox中不受支持,因此它必须是沿着以下路线的东西:
e.cancelBubble = true
或者,你可以使用FireFox的W3C标准:
e.stopPropagation();
如果你想变得更花哨,你可以这样做:
function myEventHandler(e)
{
if (!e)
e = window.event;
//IE9 & Other Browsers
if (e.stopPropagation) {
e.stopPropagation();
}
//IE8 and Lower
else {
e.cancelBubble = true;
}
}
其他回答
根据本页,在IE中你需要:
事件。cancelBubble = true
由于因果关系,我无法评论,所以我把这作为完整的答案:根据Gareth的答案(var e = arguments[0] || window.event;[…])我在onclick上使用了这个在线内联的快速hack:
<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>
我知道有点晚了,但我想让你知道,这一行写得很好。大括号返回一个事件,在这两种情况下都附加了stoppropagation -函数,所以我尝试将它们封装在大括号中,如if和....它的工作原理。:)
这也可以工作-在链接HTML使用onclick返回像这样:
<a href="mypage.html" onclick="return confirmClick();">Delete</a>
然后,comfirmClick()函数应该像这样:
function confirmClick() {
if(confirm("Do you really want to delete this task?")) {
return true;
} else {
return false;
}
};
ASP。NET网页(不是MVC),你可以使用Sys.UI.DomEvent对象作为本机事件的包装器。
<div onclick="event.stopPropagation();" ...
或者,将event作为参数传递给内部函数:
<div onclick="someFunction(event);" ...
在someFunction中:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
最好的解决方案是通过javascript函数处理事件,但为了使用一个简单而快速的解决方案,直接使用html元素,一旦“事件”和“窗口。(https://developer.mozilla.org/en-US/docs/Web/API/Window/event),我建议使用以下“硬代码”:
<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>