Javascript:如何将相同的事件侦听器重新附加到重复出现的元素上? [英] Javascript : how to re-attach the same event listener to a element reppeared?

查看:116
本文介绍了Javascript:如何将相同的事件侦听器重新附加到重复出现的元素上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我有一个内部带有h1元素的h1容器,如下所示:

In my code, I have a h1 container with h1 element inside like below :

<div id="container_h1"><h1 id="h1">Title H1</h1></div>

然后,我将事件侦听器附加到h1元素,以便在用户单击时提示h1文本h1元素:

Then, I attach an event listener to h1 element in order to alert h1 text when the user clicks on h1 element :

var h1 = document.getElementById("h1");
h1.addEventListener(
                        "click", 

                        function()
                        {
                            alert(h1.innerHTML);
                        },

                        false                       
                    );

然后,我有2个用于删除和插入h1元素的按钮,如下所示:

Then, I have 2 buttons for removing and inserting h1 element, like below :

<input type="button" value="remove H1" onclick="remove_h1();">
<input type="button" value="insert H1" onclick="insert_h1();">

//container_h1 element :
var container_h1 = document.getElementById("container_h1"); 

//Remove h1 :
function remove_h1()
{
    container_h1.innerHTML = "";    
}

//Re-appear h1 :
function insert_h1()
{
    container_h1.innerHTML = '<h1 id="h1">Title H1</h1>';   
}

问题:

当我通过单击删除H1按钮使h1元素消失时,然后单击插入H1按钮使使h1元素重新出现,然后在其中单击h1元素 h1.addEventListerner代码无效,不会触发警报

When I make disappear h1 element by clicking "remove H1" button then make reappear h1 element by clicking "insert H1" button, and then I click on h1 element, h1.addEventListerner in the code has no effect, no alert is triggered.

因此,当此h1元素重新出现时,如何将相同的事件侦听器重新附加到h1元素上?

So how can I re-attach the same event listener to h1 element when this h1 element reappears ?

谢谢。

推荐答案

而不是 h1.addEventListener(...)添加

document.body.addEventListener('click', function(element) {
    if (element.target.nodeName == 'H1') {
        // your code
    }
})

因此,您将事件监听器绑定到 body 而不是 h1
问题是您的 h1.addEventListener(...)仅应用于当前在DOM中现有的< h1> 元素,但不适用于动态创建的元素。

So you bind event listener to body rather than h1. The thing is that your h1.addEventListener(...) is only applied on currently in DOM existing <h1> elements, but not on dynamically created ones.

http ://www.theappguruz.com/blog/dynamic-event-binding-demo-jquery

在jQuery中,如何将事件附加到动态html元素上?

这篇关于Javascript:如何将相同的事件侦听器重新附加到重复出现的元素上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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