考虑以下几点:
<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的点击事件?
当前回答
使用event.stopPropagation()。
<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
对于IE: window.event.cancelBubble = true
<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
其他回答
为什么不直接检查点击了哪个元素呢?如果你点击某个东西,window.event.target被赋值给被点击的元素,被点击的元素也可以作为参数传递。
如果目标和元素不相等,则是向上传播的事件。
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />
我也有同样的问题- IE中的js错误框-据我所见,这在所有浏览器中都很好(事件。cancelBubble=true在IE中工作)
onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
这也可以工作-在链接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
}
使用这个函数,它将测试是否存在正确的方法。
function disabledEventPropagation(event)
{
if (event.stopPropagation){
event.stopPropagation();
}
else if(window.event){
window.event.cancelBubble=true;
}
}