简体   繁体   中英

An event listener is only created for the last element in forEach loop

I have a firebase database and I want to get all the chats and add an HTML element to all of them. Each div has a password input and a button. I made a forEach() loop but it only makes an event listener for the last one. I'm not very experienced so it is probably a simple problem. This is my code:

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);
    });   

Because, you are capturing the button by ID. It will capture the last ID recorded.

Instead use querySelector.

Try below, which is not a proper code, you need to tweak based on error messages.

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 type="hidden" class="childname" value="`+ childname + `">
            <input type="hidden" class="childPassword" value="`+ childPassword + `">
            <input id="`+ childName + `-input" class="password" type="password" placeholder="Enter Chat Password">
            <button id="`+ childName + `-button" class="login">Enter</button>
            </div>
        </li>
        `;
        messages.innerHTML += html;

    });
    const chatLoginContainers = document.querySelectorAll('.chat-login-container');
    chatLoginContainers.forEach((element) => {
        const loginBtn = element.querySelector('.login');
        loginBtn.addEventListener('click', (event) => {
            const childNameEle = event.target.closest('li').querySelector('.childname');
            const childPasswordEle = event.target.closest('li').querySelector('.childPassword');
            const passwordEle = event.target.closest('li').querySelector('.password');
            const childNameVal = childNameEle.value;
            const childPasswordVal = childPasswordEle.value;
            const passwordVal = passwordEle.value;
            get(ref(db, "chats/" + childNameVal)).then((snapshot) => {
                if (passwordVal == childPasswordVal) {
                    chat = childNameVal;
                    console.log("Logging in to " + childNameVal);
                    messages.innerHTML = "";
                    start();
                } else {
                    window.alert("Incorrect password, please try again");
                }
            }).catch((error) => {
                console.log(error);
            });
        })
    });

}).catch((error) => {
    console.log(error);
});   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM