我有一个firebase数据库,我想获取所有聊天记录,并在其中添加一个HTML元素.每个div都有一个密码输入和一个按钮.我创建了一个forEach()循环,但它只为最后一个循环创建一个事件侦听器.我不是很有经验,所以这可能是一个简单的问题.这是我的代码:
get(ref(db, "chats")).then((snapshot)=>{
snapshot.forEach((child)=>{
var html = "";
var childName = child.val().chatname;
var childPassword = child.val().chatpassword;
console.log(childName);
html += `
<li>
<div class="chat-login-container">
<h3>`+childName+`</h3>
<input id="`+childName+`-input" type="password" placeholder="Enter Chat Password">
<button id="`+childName+`-button" class="login">Enter</button>
</div>
</li>
`;
messages.innerHTML += html;
var button = document.getElementById(childName+"-button");
var passwordInput = document.getElementById(childName+"-input");
button.addEventListener("click", ()=>{
get(ref(db, "chats/"+childName)).then((snapshot) =>{
if(passwordInput==childPassword){
chat = childName;
console.log("Logging in to "+childName);
messages.innerHTML = "";
start();
}else{
window.alert("Incorrect password, please try again");
}
}).catch((error)=>{
console.log(error);
});
});
});
}).catch((error)=>{
console.log(error);
});