Javascript 3 个链接上的 addEventListener,只有 1 个有效

Javascript addEventListener on 3 links, only 1 working

我正在尝试使用以下代码在我的 link 上动态添加事件侦听器(当然用不同的 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 links,但第二行仅在第三个 link.

上附加了事件

我猜你没有足够的信息来解决这个问题,但也许你可以给我一些提示,我应该看看哪里。


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

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 中进行逐步调试,似乎每个 link 都会在下一个

时丢失点击事件
 container.innerHTML += '<hr />'; 

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

我模拟了你的代码,它对我来说工作正常。

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 错误没有改变。很难用提供的片段来判断

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

由此,我找到了这个问题: Manipulating innerHTML removes the event handler of a child element? 我能够通过使用解决我的问题:

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