【发布时间】:2016-03-26 21:42:17
【问题描述】:
我正在尝试使用以下代码在我的链接上动态添加事件侦听器(当然,使用不同的 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(这个或另一个)会删除添加的事件侦听器?
【问题讨论】:
-
您应该只显示更多代码,以便我们了解
this的闭包是什么,或者关注您的包装环境。 -
如果你能发布一个最小但可验证的示例代码,HTML,JS ...
-
我相信你需要使用 IIFE。请为我们发布更多代码以更好地帮助您。
-
发布了更多代码,并且由于链接的 innerHTML 在第一个 getElementById 中使用正确的 id 进行了更新,我认为 ID 不是问题:我得到 yahoooo1、yahooooo2、yahooooo3、yahoooo4显示
标签: javascript dom-events addeventlistener