簡體   English   中英

3個鏈接上的Javascript addEventListener,僅1個有效

[英]Javascript addEventListener on 3 links, only 1 working

我正在嘗試使用以下代碼在我的鏈接上動態添加事件偵聽器(被調用3次,當然使用不同的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('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中進行逐步調試,似乎每個鏈接在下一次鏈接丟失時都會丟失click事件。

 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沒有更改。 用提供的代碼片段很難說

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM