javascript addEventListener without selecting children

后端 未结 3 917
醉酒成梦
醉酒成梦 2021-01-02 01:04

I need to use javascript only for this project. Sorry, no jQuery (I feel ashamed as well).

I am adding an addEventListener to a div. \"Problem\

3条回答
  •  迷失自我
    2021-01-02 01:39

    You can tell which element the event actually fired on by reading event.target in your callback.

    var el = ...
    el.addEventListener('click', function(event){
      if (el !== event.target) return;
    
      // Do your stuff.
    
    }, false);
    

    The other option would be to have handlers bound to the child elements to prevent the event from reaching the parent handler, but that is more work and potentially hides events from things that might actually be listening for them above the parent.

    Update

    Given your example code, you should be able to do this.

    var el = document.getElementById(myObj.id);
    el.addEventListener("mousedown", myObjDown, false);
    
    function myObjDown(event) {
      if (el !== event.target) return;
    
      //do stuff here
    }
    

    Also as a general note, keep in mind that none if this will work on IE < 9 because addEventListener is not supported on those.

提交回复
热议问题