简体   繁体   English

如何使用内联 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的点击事件?

Use event.stopPropagation() .使用event.stopPropagation()

<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>

For IE: window.event.cancelBubble = true对于 IE: window.event.cancelBubble = true

<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>

There are two ways to get the event object from inside a function:有两种方法可以从函数内部获取事件对象:

  1. The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)第一个参数,在符合 W3C 的浏览器(Chrome、Firefox、Safari、IE9+)中
  2. The window.event object in Internet Explorer (<=8) Internet Explorer 中的 window.event 对象 (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:如果您需要支持不遵循 W3C 建议的旧浏览器,通常在一个函数中您将使用如下所示的内容:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable.它将检查第一个,然后检查另一个并存储在事件变量中找到的任何一个。 However in an inline event handler there isn't an e object to use.但是,在内联事件处理程序中,没有要使用的e对象。 In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:在这种情况下,您必须利用始终可用的arguments集合,并引用传递给函数的完整参数集:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation.但是,一般来说,如果您需要处理诸如停止传播之类的复杂操作,您应该避免使用内联事件处理程序。 Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.从中长期来看,单独编写事件处理程序并将它们附加到元素是一个更好的主意,无论是可读性还是可维护性。

Keep in mind that window.event is not supported in FireFox, and therefore it must be something along the lines of:请记住,FireFox 不支持 window.event,因此它必须符合以下条件:

e.cancelBubble = true

Or, you can use the W3C standard for FireFox:或者,您可以使用 FireFox 的 W3C 标准:

e.stopPropagation();

If you want to get fancy, you can do this:如果你想花哨,你可以这样做:

function myEventHandler(e)
{
    if (!e)
      e = window.event;

    //IE9 & Other Browsers
    if (e.stopPropagation) {
      e.stopPropagation();
    }
    //IE8 and Lower
    else {
      e.cancelBubble = true;
    }
}

Use this function, it will test for the existence of the correct method.使用此功能,它将测试是否存在正确的方法。

function disabledEventPropagation(event)
{
   if (event.stopPropagation){
       event.stopPropagation();
   }
   else if(window.event){
      window.event.cancelBubble=true;
   }
}

我有同样的问题 - IE 中的 js 错误框 - 就我所见,这在所有浏览器中都可以正常工作(event.cancelBubble=true 在 IE 中完成这项工作)

onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"

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>

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
}

According to this page , in IE you need:根据此页面,在 IE 中您需要:

event.cancelBubble = true event.cancelBubble = true

I cannot comment because of Karma so I write this as whole answer: According to the answer of Gareth (var e = arguments[0] || window.event; [...]) I used this oneliner inline on the onclick for a fast hack:由于业力,我无法发表评论,所以我将其写为完整答案:根据 Gareth (var e = arguments[0] || window.event; [...]) 的答案,我在 onclick 上使用了此 oneliner inline for a快速破解:

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

I know it's late but I wanted to let you know that this works in one line.我知道现在已经晚了,但我想让你知道这在一行中有效。 The braces return an event which has the stopPropagation-function attached in both cases, so I tried to encapsulate them in braces like in an if and....it works.大括号返回一个事件,该事件在这两种情况下都附加了 stopPropagation 函数,因此我尝试将它们封装在大括号中,例如 if 和....它可以工作。 :) :)

Why not just check which element was clicked?为什么不检查点击了哪个元素? If you click on something, window.event.target is assigned to the element which was clicked, and the clicked element can also be passed as an argument.如果你点击的东西, window.event.target分配给哪个被点击的元素,点击的元素也可以作为参数传递。

If the target and element aren't equal, it was an event that propagated up.如果目标和元素不相等,则是向上传播的事件。

function myfunc(el){
  if (window.event.target === el){
      // perform action
  }
}
<div onclick="myfunc(this)" />

This also works - In the link HTML use onclick with return like this :这也有效 - 在链接 HTML 中使用 onclick 并返回如下:

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

最好的解决方案是通过 javascript 函数处理事件,但是为了使用直接使用 html 元素的简单快速的解决方案,一旦“事件”和“window.event”被弃用并且不被普遍支持( https://developer.mozilla.org/en-US/docs/Web/API/Window/event ),我建议使用以下“硬代码”:

<div onclick="alert('blablabla'); (arguments[0] ? arguments[0].stopPropagation() : false);">...</div>

Use separate handler, say:使用单独的处理程序,例如:

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

and in html do this:并在 html 中这样做:

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

Or even :甚至:

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

for:用于:

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

is the current norm, and the one thing that worked for me.是当前的规范,也是对我有用的一件事。 See: https://developer.mozilla.org/en-US/docs/Web/API/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;
}

this worked in the latest Chrome, Opera, and IE.这适用于最新的 Chrome、Opera 和 IE。 (the Mozilla page indicates Firefox would do it too, so I don't even test it ) (Mozilla 页面显示 Firefox 也会这样做,所以我什至不测试它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM