javascript addEventListener without selecting children

后端 未结 3 918
醉酒成梦
醉酒成梦 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.

    0 讨论(0)
  • 2021-01-02 01:40

    Here's an alternative, which keeps your myObjDown function in line with a typical event handler. (using e.target as reference to the event invoking element)

    var CssSelector = "div.className";
    var elms = document.querySelectorAll(CssSelector);
    
    for (i = 0; i < elms.length; i++) {
        elms[i].addEventListener("mousedown", myObjDown.bind(null, {"target":elms[i]}, false);
    }
    
    function myObjDown(e) {
      console.log("event: %o - target: %o", e, e.target);
    
      var elm = e.target;
      //do stuff here
    }
    

    It was suggested that ..

    this method could cause memory leaks with versions of some browsers. If anyone experiences this or has any valuable insights. Please comment.


    an alternative, in this regard would be

    var CssSelector = "div.className";
    var elms = document.querySelectorAll(CssSelector);
    
    for (i = 0; i < elms.length; i++) {
        elms[i].addEventListener("mousedown", myObjDown.bind(null, elms[i].id}, false);
    }
    
    function myObjDown(id) {
      console.log("element: %o ", document.getElementById(id));
    
      //do stuff here
    }
    
    0 讨论(0)
  • 2021-01-02 01:55

    You can use the currentTarget Event Property

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

    More details: https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget

    0 讨论(0)
提交回复
热议问题