本文翻译自:How to stop event propagation with inline onclick attribute?
Consider the following: 考虑以下:
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
How can I make it so that when the user clicks the span, it does not fire the div
's click event? 我怎样才能使它在用户单击跨度时不会触发div
的click事件?
#1楼
参考:https://stackoom.com/question/1cro/如何使用内联onclick属性停止事件传播
#2楼
我遇到了同样的问题-IE中的js错误框-就我所知,这在所有浏览器中都可以正常运行(event.cancelBubble = true在IE中可以完成工作)
onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
#3楼
This also works - In the link HTML use onclick with return like this : 这也有效-在链接HTML中,将onclick与return一起使用,如下所示:
<a href="mypage.html" onclick="return confirmClick();">Delete</a>
And then the comfirmClick() function should be like: 然后,comfirmClick()函数应类似于:
function confirmClick() {
if(confirm("Do you really want to delete this task?")) {
return true;
} else {
return false;
}
};
#4楼
For ASP.NET web pages (not MVC), you can use Sys.UI.DomEvent
object as wrapper of native event. 对于ASP.NET网页(不是MVC),可以将Sys.UI.DomEvent
对象用作本机事件的包装。
<div onclick="event.stopPropagation();" ...
or, pass event as a parameter to inner function: 或者,将事件作为参数传递给内部函数:
<div onclick="someFunction(event);" ...
and in someFunction: 并在someFunction中:
function someFunction(event){
event.stopPropagation(); // here Sys.UI.DomEvent.stopPropagation() method is used
// other onclick logic
}
#5楼
This worked for me 这对我有用
<script>
function cancelBubble(e) {
var evt = e ? e:window.event;
if (evt.stopPropagation) evt.stopPropagation();
if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>
<div onclick="alert('Click!')">
<div onclick="cancelBubble(event)">Something inside the other div</div>
</div>
#6楼
<div onclick="alert('you clicked the header')" class="header">
<span onclick="alert('you clicked inside the header'); event.stopPropagation()">
something inside the header
</span>
</div>