考虑以下几点:
<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的点击事件?
当前回答
最好的解决方案是通过javascript函数处理事件,但为了使用一个简单而快速的解决方案,直接使用html元素,一旦“事件”和“窗口。(https://developer.mozilla.org/en-US/docs/Web/API/Window/event),我建议使用以下“硬代码”:
<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>
其他回答
这对我很有效
<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>
Event.preventDefault()
是目前的标准,也是对我有效的一种方法。参见:https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
<button value=login onclick="login(event)">login</button>
//and in a script tag
function login(ev){
ev.preventDefault()
return false;
}
这在最新的Chrome、Opera和IE中都有效。(Mozilla页面显示Firefox也会这样做,所以我甚至没有测试它!)
这也可以工作-在链接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;
}
};
<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>
为什么不直接检查点击了哪个元素呢?如果你点击某个东西,window.event.target被赋值给被点击的元素,被点击的元素也可以作为参数传递。
如果目标和元素不相等,则是向上传播的事件。
function myfunc(el){
if (window.event.target === el){
// perform action
}
}
<div onclick="myfunc(this)" />