考虑以下几点:

<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.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也会这样做,所以我甚至没有测试它!)

其他回答

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;
   }
}

由于因果关系,我无法评论,所以我把这作为完整的答案:根据Gareth的答案(var e = arguments[0] || window.event;[…])我在onclick上使用了这个在线内联的快速hack:

<div onclick="(arguments[0] || window.event).stopPropagation();">..</div>

我知道有点晚了,但我想让你知道,这一行写得很好。大括号返回一个事件,在这两种情况下都附加了stoppropagation -函数,所以我尝试将它们封装在大括号中,如if和....它的工作原理。:)

使用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>

使用单独的处理程序,比如:

function myOnClickHandler(th){
//say let t=$(th)
}

在HTML中这样做:

<...onclick="myOnClickHandler(this); event.stopPropagation();"...>

甚至:

function myOnClickHandler(e){
  e.stopPropagation();
}

for:

<...onclick="myOnClickHandler(event)"...>