考虑以下几点:
<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的点击事件?
当前回答
<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>
其他回答
<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>
根据本页,在IE中你需要:
事件。cancelBubble = true
从函数内部获取事件对象有两种方法:
第一个参数,在w3c兼容的浏览器中(Chrome、Firefox、Safari、IE9+) 窗外。Internet Explorer中的事件对象(<=8)
如果你需要支持不符合W3C推荐标准的旧浏览器,一般在函数中你会使用如下代码:
function(e) {
var event = e || window.event;
[...];
}
这将检查第一个,然后是另一个,并存储在事件变量中找到的任何一个。然而,在内联事件处理程序中,没有e对象可以使用。在这种情况下,你必须利用arguments集合,它总是可用的,并引用传递给函数的完整参数集:
onclick="var event = arguments[0] || window.event; [...]"
但是,一般来说,如果需要处理像停止传播这样复杂的事情,就应该避免使用内联事件处理程序。从中期和长期来看,单独编写事件处理程序并将它们附加到元素上是一个更好的想法,这对可读性和可维护性都有好处。
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
}
记住那个窗口。事件在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;
}
}