仅使用Javascript将AddEventListener添加到不存在的对象 [英] AddEventListener to not exists object with only Javascript

查看:141
本文介绍了仅使用Javascript将AddEventListener添加到不存在的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索整个stackoverflow但是我没有得到任何好的结果来解决这个问题。如果我错了,请更正我。

I search for the whole stackoverflow but I didn't get any good result against this issues.Correct me if i'm wrong.

我想将addEventListener添加到DOM中存在或不存在的对象。

I want to addEventListener to object that exists or haven't exists in DOM.

在Jquery,我们可以简单地执行以下代码:

In Jquery we can simply do the code below:

$('document').on('click', '.my-button', function () {
    alert("work!!!");
});

但我怎样才能使用Javascript来实现它呢?以下是我的源代码。但是在页面加载后,所有新添加的对象都没有附加点击事件。

But how can I use only Javascript to acheive it? Below is my source code. But after the page loaded, all the new added object doesn't attach a click event.

var Button = document.getElementsByClassName("my-button");
for(i=0;i<Button.length;i++){
    document.getElementsByClassName("my-button")[i].addEventListener("click",function(){
        alert("Work!!!!");
    });
}

提供任何建议。

推荐答案

jQuery不会将事件监听器添加到每个div,它会将其附加到父级。

jQuery does not add the event listener to each div, it attaches it to the parent.

你能做什么将事件附加到父级,并在事件处理程序中,看到目标是其中一个按钮,然后运行您的函数

What you can do is attach the event to the parent, and in the event handler, see it the target is one of the buttons, then run your function

HTML

<div id="parent">
     <div class="my-button">one</div>
     <div class="my-button">two</div>
     <div class="my-button">three</div>
</div>

JS

document.getElementById("parent").addEventListener("click", function(event) {
     if ( event.target.className === 'my-button') {
          //Do your magic
     }
});

这样,您添加的每个按钮都将运行您的功能。
我不知道事件目标是否具有className属性,但我认为基于event.target对象获取元素相当简单。
请记住,旧的IE不会有addEventListener函数。点击此处 EventTarget.addEventListener - Web API接口| MDN

This way, every button you add will run your function. I don't know if the event target has the className attribute, but I suppose is rather simple to get the element based on the event.target object. Remember that older IE won't have the addEventListener function. Check here EventTarget.addEventListener - Web API Interfaces | MDN

这篇关于仅使用Javascript将AddEventListener添加到不存在的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆