Javascript在3个链接上添加EventListener,只有1个可用

Javascript addEventListener on 3 links, only 1 working

本文关键字:只有 1个 EventListener 添加 3个 链接 Javascript      更新时间:2023-09-26

我正试图用以下代码在链接上动态添加事件侦听器(当然,用不同的this.newsPost.id调用了3次):

document.getElementById('user_news_post_comment_add_button_show_form_' + this.newsPost.id).innerHTML = 'yahoooooo' + this.newsPost.id;
document.getElementById('user_news_post_comment_add_button_show_form_' + this.newsPost.id).addEventListener('click', function() {alert('alert');});

第一行是调试行,查看访问DOM事件是否有问题。但令人惊讶的是,第一行用yahooooo1或2或3更新了3个链接,但第二行只在第三个链接上附加了事件。

我想你没有足够的信息来解决这个问题,但也许你可以给我一些提示,让我去看看。


为了提供更多信息,我在这里循环:

for (var i = 0; i < newsPostArray.length; ++i) {
    if (i != 0) {
        container.innerHTML += '<hr />';
    }
    this.showNewsPostSingle(container, newsPostArray[i]);
}

然后我有:

UserNewsPostList.prototype.showNewsPostSingle = function (container, newsPost) {
    var content = '<div class="user_news_post">';
    content += '<div id="user_news_post_comment_' + newsPost.id + '" class="user_news_post_comment"></div>';
    content += '</div>';
    container.innerHTML += content;
    new UserNewsPostListComment(newsPost).show(document.getElementById('user_news_post_comment_' + newsPost.id));
};

哪个调用:

function UserNewsPostListComment(newsPost) {
    this.newsPost = newsPost;
}
UserNewsPostListComment.prototype.show = function(container) {
    var content = '';
    content += this.getNewsPostHTMLSingleCommentPartAdd();
    container.innerHTML = content;
    window.console.log(this.newsPost.id);
    document.getElementById('user_news_post_comment_add_button_show_form_' + this.newsPost.id).innerHTML = 'yahoooooo' + this.newsPost.id;
    document.getElementById('user_news_post_comment_add_button_show_form_' + this.newsPost.id).addEventListener('click', function() {alert('attachEvents');});
};
UserNewsPostListComment.prototype.getNewsPostHTMLSingleCommentPartAdd = function() {
    var content = '<div class="user_news_post_comment_add">';
    content += '<a id="user_news_post_comment_add_button_show_form_' + this.newsPost.id + '">LINK</a>';
    content += '</div>';
    return content;
};

控制台显示:4.3.2.1


附加更新:通过使用开发工具在Chrome中进行一步一步的调试,似乎每个链接都会在下一个中丢失点击事件

 container.innerHTML += '<hr />'; 

在第一循环中执行。为什么附加到父innerHTML(这个或另一个)会删除添加的事件侦听器?

通过逐行调试,我发现下一个.innerHTML+=正在删除事件。

从中,我发现了这个问题:操作innerHTML是否删除子元素的事件处理程序?我能够通过使用来解决我的问题

.insertAdjacentHTML('beforeend', 'test');
// instead of
.innerHTML += 'test';

我模拟了您的代码,它对我来说运行良好。

https://jsfiddle.net/zqt4bjtt/

以下JS代码用于模拟。请参阅jsfiddle了解完整的模拟

id = 1;
while(id < 4){
    document.getElementById('user_news_post_comment_add_button_show_form_' + id).innerHTML = 'yahoooooo' + id;
    document.getElementById('user_news_post_comment_add_button_show_form_' + id).addEventListener('click', function() {alert(this.id);});
  id++;
}

可能是错误,可能是您的this.newsPost.id没有更改。提供的片段很难说