简体   繁体   中英

How do I get the index of a clicked button?

I'm creating a trivia game where you have to guess the name of some countries's flags. I used querySelectorAll to select all the input fields and all the button that you have to click to actually execute the GUESS code. I also made an object named "flags" with the correct answers. I need to get the index of the button I pressed to compare the input value with the index of the button and the index of the flags object since they have the same index to check if the input value matches with the flag.

I did a for loop that iterated through all of the values and when I press a button it checks all of the inputs instead of just the one I'm clicking. I just want it to check the one I'm clicking.

const inputs = document.querySelectorAll(".input-flag");
const buttons = document.querySelectorAll(".btn");
const btns = Array.from(buttons);

const flags = [
    "belgium",
    "spain",
    "italy",
    "argentina",
    "venezuela",
    "brazil"
];

buttons.forEach((button) => {
    button.addEventListener("click", (e) => {

        for(let i = 0; i < btns.length; i++) {

            if(btns[i].previousElementSibling.value === flags[i]) {
                console.log("correct");
            } else {
                console.log("incorrect");
            }
        }


    })
});

So when I click a button and three input fields are correct and three are incorrect, it logs 3 corrects and 3 incorrects. I've been searching stuff for hours but can't find a solution. I don't know if I explained myself well, I'm a beginner :(

I want to click a button and just check for its corresponding input field value

Assuming that buttons, inputs and flags are ordered in same way:

buttons.forEach((button, index) => {
    button.addEventListener("click", () => {
        const input = inputs[index];
        const flag = flags[index];
        if (input.value == flag) {
            console.log("correct");
        } else {
            console.log("incorrect");
        }
    })
});

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