How to stop event propagation with inline onclick attribute?

前端 未结 13 2085
情书的邮戳
情书的邮戳 2020-11-21 23:46

Consider the following:

相关标签:
13条回答
  • 2020-11-22 00:31

    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:

    <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. :)

    0 讨论(0)
  • 2020-11-22 00:35

    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.

    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)" />
    
    0 讨论(0)
  • 2020-11-22 00:36

    I had the same issue - js error box in IE - this works fine in all browsers as far as I can see (event.cancelBubble=true does the job in IE)

    onClick="if(event.stopPropagation){event.stopPropagation();}event.cancelBubble=true;"
    
    0 讨论(0)
  • 2020-11-22 00:45
    <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>
    
    0 讨论(0)
  • 2020-11-22 00:46

    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;
       }
    }
    
    0 讨论(0)
  • 2020-11-22 00:48

    Use event.stopPropagation().

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

    For IE: window.event.cancelBubble = true

    <span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
    
    0 讨论(0)
提交回复
热议问题