Adding an event listener to an element that doesn't exist yet in vanilla javascript

前端 未结 4 2322
我在风中等你
我在风中等你 2021-02-18 16:23

In JQuery I can do:

$(document).on(\"click\",\"a.someBtn\",function(e){
    console.log(\"hi\");
});

to add an event listener to an element th

4条回答
  •  梦谈多话
    2021-02-18 16:49

    Here's a function that will let you add "live" events like jQuery's .on. It can be invoked like this:

    addLiveListener(scope, selector, event, function reference);
    

    Take a look at the function comment for the description of each of those parameters.

    /**
     * Adds a istener for specific tags for elements that may not yet
     * exist.
     * @param scope a reference to an element to look for elements in (i.e. document)
     * @param selector the selector in form [tag].[class] (i.e. a.someBtn)
     * @param event and event (i.e. click)
     * @param funct a function reference to execute on an event
     */
    function addLiveListener(scope, selector, event, funct) {
      /**
       * Set up interval to check for new items that do not 
       * have listeners yet. This will execute every 1/10 second and
       * apply listeners to 
       */
      setInterval(function() {
        var selectorParts = selector.split('.');
        var tag = selectorParts.shift();
        var className;
        if (selectorParts.length)
          className = selectorParts.shift();
    
        if (tag != "") {
          tag = tag.toUpperCase();
          var elements = scope.getElementsByTagName(tag);
        } else
          var elements = scope.getElementsByClassName(className);
    
        for (var i = 0; i < elements.length; i++) {
          if (elements[i][event + '_processed'] === undefined && (tag == "" || elements[i].tagName == tag)) {
            elements[i].addEventListener(event, funct);
          }
        }
      }, 1000);
    }
    

    And here's a full working demo:

    /**
     * Adds another anchor with no events attached and lets 
     * our other code auto-attach events
     */
    var currentAnchor = 3;
    
    function addAnchor() {
      currentAnchor++;
      var element = document.createElement('a');
      element.href = "#";
      element.innerHTML = "Anchor " + currentAnchor;
      element.className = "someBtn";
      document.getElementById("holder").appendChild(element);
    }
    
    /**
     * Adds a istener for specific tags for elements that may not yet
     * exist.
     * @param scope a reference to an element to look for elements in (i.e. document)
     * @param selector the selector in form [tag].[class] (i.e. a.someBtn)
     * @param event and event (i.e. click)
     * @param funct a function reference to execute on an event
     */
    function addLiveListener(scope, selector, event, funct) {
      /**
       * Set up interval to check for new items that do not 
       * have listeners yet. This will execute every 1/10 second and
       * apply listeners to 
       */
      setInterval(function() {
        var selectorParts = selector.split('.');
        var tag = selectorParts.shift();
        var className;
        if (selectorParts.length)
          className = selectorParts.shift();
    
        if (tag != "") {
          tag = tag.toUpperCase();
          var elements = scope.getElementsByTagName(tag);
        } else
          var elements = scope.getElementsByClassName(className);
    
        for (var i = 0; i < elements.length; i++) {
          if (elements[i][event + '_processed'] === undefined && (tag == "" || elements[i].tagName == tag)) {
            elements[i].addEventListener(event, funct);
          }
        }
      }, 1000);
    }
    
    /**
     * Now let's add live listener for "a" tags
     */
    addLiveListener(document, "a.someBtn", "click", function() {
      alert('Clicked ' + this.innerHTML);
    });
    a {
      margin-right: 10px;
    }
    
    

    Anchor 1Anchor 2Anchor 3

提交回复
热议问题