如何使用内联onclick属性停止事件传播?

本文翻译自: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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值