将事件侦听器添加到vanilla javascript中尚不存在的元素

时间:2015-06-02 16:31:06

标签: javascript jquery

在JQuery中我可以做到:

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

将事件侦听器添加到尚不存在的元素。我似乎无法弄清楚如何将事件监听器添加到尚未存在于vanilla javascript中的元素中。
以下不起作用:

query.addEventListener( "click", someListener );

修改

我想要做的是通过查询选择器比较项目。我正在选择querySelectorAll尚不存在的元素。它比仅仅检查标签名称更具动态性。

4 个答案:

答案 0 :(得分:15)

使用event对象中的target属性获取单击的元素。然后,手动测试类型/属性/ ID

document.addEventListener( "click", someListener );

function someListener(event){
    var element = event.target;
    if(element.tagName == 'A' && element.classList.contains("someBtn")){
        console.log("hi");
    }
}

答案 1 :(得分:2)

您可以使用event.target

  

对调度事件的对象的引用。

代码

(function () {
    "use strict";
        document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
        if (e.target.tagName == 'A' && e.target.classList.contains("someBtn")) {
          alert('Clicked');
        }
      }, false);
})();

(function() {
  "use strict";
  var a = document.createElement('a');
  a.textContent = 'Click Me';
  a.href = '#';
  document.body.appendChild(a);

  document.getElementsByTagName('body')[0].addEventListener('click', function(e) {
    if (e.target.tagName == 'A') {
      alert('Clicked');
    }
  }, false);
})();

答案 2 :(得分:1)

这是一个可以让你添加像jQuery .on这样的“实时”事件的函数。它可以像这样调用:

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

查看函数注释,了解每个参数的描述。

/**
 * 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);
}

这是一个完整的演示版:

/**
 * 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;
}
<!-- Add some pre-existing anchors -->
<p id="holder">
  <a href="#" class="someBtn">Anchor 1</a><a href="#" class="someBtn">Anchor 2</a><a href="#" class="someBtn">Anchor 3</a>
</p>

<!-- A button to add dynamic new anchors -->
<input type="button" value="Add anchor" onclick="addAnchor();" />

答案 3 :(得分:0)

您想要的是使用DOM MutationObserver事件来应用addEventListener。自2012年以来,我认为这个DOM API可用于所有主流浏览器。

我使用它来降低由其代码段(https://www.w3schools.com/howto/howto_google_translate.asp)创建的Google翻译栏。由于它动态创建元素(iframe),因此您遇到的问题也是如此。只需根据需要更改回调函数和变量。

//Observer for Google translator bar creation and action to move to bottom
// Select the nodetree that will be observed for mutations
var nodetree = document.getElementsByTagName("body")[0];
// Select the target node atributes (CSS selector)
var targetNode = "iframe.goog-te-banner-frame";
// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true };
// Callback function to execute when mutations of DOM tree are observed
var lowerGoogleTranslateBar = function(mutations_on_DOMtree) {
    for(var mutation of mutations_on_DOMtree) {
        if (mutation.type == 'childList') {
            console.log(mutation);
            if (document.querySelector(targetNode) != null) {
                //40px is the height of the bar
                document.querySelector(targetNode).style.setProperty("top", "calc(100% - 40px)");
                //after action is done, disconnect the observer from the nodetree
                observerGoogleTranslator.disconnect();
            }
        }
    }
};
// Create an observer instance linked to the callback function
var observerGoogleTranslator = new MutationObserver(lowerGoogleTranslateBar);
// Start observing the target node for configured mutations
observerGoogleTranslator.observe(nodetree, config);

您可以在此处了解详情:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver