Javascript Event Bubbling

后端 未结 2 557
时光说笑
时光说笑 2020-12-06 22:20

I have this setup

1 2 3
2条回答
  •  醉酒成梦
    2020-12-06 22:28

    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.

提交回复
热议问题