Javascript Event Bubbling

喜欢而已 提交于 2019-11-27 04:47:55

问题


I have this setup

<div onclick="SomeEvent">
    <input type=checkbox value=1>1
    <input type=checkbox value=2>2
    <input type=checkbox value=3>3
</div>

The problem when the user click on the checkboxes I don't want the SomeEvent fired.

In the some event I do have the line
"event.stopPropagation();"
but that seems to do nothing at all.


回答1:


In the event bubbling model, the event propagation is from the inner elements to the outer elements.

This means that the event.stopPropagation(); should be in the inputs' events instead of the div.

<div onclick="SomeEvent">
  <input type=checkbox value=1 onclick="stopPropagation()">1
  <input type=checkbox value=2 onclick="stopPropagation()>2
  <input type=checkbox value=3 onclick="stopPropagation()>3
</div>

Now the Javascript code:

function stopPropagation() {
  //... do something.
  //stop propagation:
  if (!e) var e = window.event;
  e.cancelBubble = true; //IE
  if (e.stopPropagation) e.stopPropagation(); //other browsers
}

More info: http://www.quirksmode.org/js/events_order.html

EDIT: The above was a quick way to show how the bubbling model works, but a better answer to solve this problem using JQuery would be:

<div id="mydiv">
  <input type="checkbox" value="1" /> 1
  <input type="checkbox" value="2" /> 2
  <input type="checkbox" value="3" /> 3
</div>

Now the Javascript code:

$('#mydiv').click(function(e) {
  //do something
});

$('#mydiv input').click(function(e) {
  //stop propagation:
  if (!e) var e = window.event;
  e.cancelBubble = true; //IE
  if (e.stopPropagation) e.stopPropagation(); //other browsers
});



回答2:


Change the inline onclick to this:

onclick="SomeEvent(this, event)"

Then in SomeEvent, do this:

function SomeEvent( el, event ) {
    var target = event.srcElement || event.target;

    if( el === target ) {
        // run your code
    }
}

This will only fire the code when you click on the div element itself, instead of a descendant.

If there are other descendants that should fire the handler, then do this:

function SomeEvent( el, event ) {
    var target = event.srcElement || event.target;

    if( target.nodeName.toLowerCase() !== 'input' || !target.type || target.type !== 'checkbox' ) {
        // run your code
    }
}

This will fire the handler for any click except those on the checkboxes.



来源:https://stackoverflow.com/questions/5971601/javascript-event-bubbling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!