我正在使用Node.js和Jade创建博客引擎,并遍历每条帖子,为他们提供一个按钮,可以删除该帖子。无论出于何种原因,当我单击按钮时,无论我单击哪个按钮,它都只为我提供最后一个帖子的ID的模态,仅使我能够删除最后一个帖子。有人可以给我一个解释吗?这是我的代码:
each post in postsList
div#post-container(class='container-fluid')
.row
.col-md-6
a(href='/blog/posts/#{post._id}')
h2 #{post.title}
h4 Date and Time posting
img#post-img(src=urlList[i])
.col-md-1.offset-md-5
if isAdmin
div(id='#{post._id}Modal' style='display:none;')
p #{post._id}
// Modal content
.modal-content
.modal-header
span.closeDeletePost ×
h2 Modal Header
.modal-body
p Are you sure you want to delete post?
.modal-footer
a(href="api/blog/posts/#{post._id}/delete")
button Yes
button.closeDeletePost No
button.xxx(id='#{post._id}') X
script.
var postId = "#{post._id}"
// Get the modal
var deletePostModal = document.getElementById(postId + 'Modal');
// Get the button that opens the modal
var deletePostBtn = document.getElementById(postId);
// Get the <span> element that closes the modal
var closeDeletePost = document.getElementsByClassName("closeDeletePost")[0];
// When the user clicks the button, open the modal
deletePostBtn.onclick = function() {
deletePostModal.style.display = "block";
};
// When the user clicks on <span> (x), close the modal
closeDeletePost.onclick = function() {
deletePostModal.style.display = "none";
};
// Modal ID output for all buttons is 5b64a45fe1f29c1f1448c21f
// I can only delete last post, no matter which post btn is clicked
// I want to delete any post, according to which btn I click
感谢所有帮助!
答案 0 :(得分:0)
在JavaScript中,只有两个作用域;全局和功能范围。您的所有var
都具有相同的全局范围,这是一个问题。对于每次循环迭代,脚本代码都在相同的范围内执行。所有变量都在变化,当循环结束时,它们将等于上一次迭代中的变量。现在,例如,每个deletePostBtn
函数中的变量.onClick
引用全局范围内的deletePostBtn
变量。当您单击按钮时,for循环已经完成,并且deletePostBtn
变量将等于在上一次循环迭代中为其分配的值。因此,现在每个.onClick
函数都引用相同的值。
在函数中包装逻辑将创建一个新的本地/函数作用域。现在,它不再postId
更新每次迭代,而将在迭代时将作用域限定为函数,并且在将来保持不变。
请参见下面的代码示例。我将代码简化为问题的症结所在。
之前 :(不起作用)
each post in postsList
button(id='#{post._id}') #{post.title}
script.
var postId = "#{post._id}"
var deletePostBtn = document.getElementById(postId);
deletePostBtn.onclick = function() {
deletePostBtn.style.display = "none";
};
之后:(工作中)
each post in postsList
button(id='#{post._id}') #{post.title}
script.
function createOnClick(postId) {
var deletePostBtn = document.getElementById(postId);
deletePostBtn.onclick = function() {
deletePostBtn.style.display = "none";
};
}
createOnClick("#{post._id}")