简体   繁体   English

是否可以使用回调 function 将单击事件中的按钮值存储在全局变量上?

[英]Is it possible to store a button value from a click event on a global variable using a callback function?

I'm trying to store the value from one of three buttons in a variable called " playerScore ", so it can be compared to another variable.我试图将来自三个按钮之一的值存储在一个名为“ playerScore ”的变量中,因此它可以与另一个变量进行比较。 However, the code below is returning "undefined" instead of the actual value of the button clicked by the user.但是,下面的代码返回“未定义”而不是用户单击的按钮的实际值。

I'm using a callback function in order to retrieve the value from the click event.我正在使用回调 function 来从点击事件中检索值。 If I simply console.log the event, it runs .如果我只是 console.log 事件,它会运行 However if I try to store it in the global variable "playerScore" and then console.log it, it doesn't.但是,如果我尝试将它存储在全局变量“playerScore”中,然后将其存储在 console.log 中,它不会。

I'm sure there's a better and simpler way to do it, but I'm out of ideas.我确信有更好更简单的方法来做到这一点,但我没有想法。 Any help is highly appreciated.非常感谢任何帮助。

If I run the code below, the function returns " undefined ":如果我运行下面的代码,function 返回“ undefined ”:

// Gets player choice from button click (iterates nodelist of buttons)
let playerChoice;
function getPlayerChoice() {
    const playerButtons = document.querySelectorAll(".btn");
    for (i of playerButtons) {
        (function(i) {
            i.addEventListener('click', function() {
              playerChoice = i.innerText;
            });
        })(i);     
    }
    console.log(playerChoice);
}

If I run the code below, it works and console logs the value of the button click:如果我运行下面的代码,它会工作并且控制台会记录按钮单击的值:

function getPlayerChoice() {
    const playerButtons = document.querySelectorAll(".btn");
    for (i of playerButtons) {
        (playerChoice = function(i) {
            i.addEventListener('click', function() {
                console.log(i.innerText);
            });
        })(i);     
    }
}

The getPlayerChoice() function gets called in the following function: getPlayerChoice() function 在以下 function 中被调用:

function playRound(playerSelection, computerSelection) {

    // Gets player and computer choices
    playerSelection = getPlayerChoice();
    computerSelection = getComputerChoice();
}

In your first example, the console.log is being evaluated before any button is pressed, and will therefore print undefined .在您的第一个示例中,在按下任何按钮之前正在评估console.log ,因此将打印undefined

To print a meaningful value, the logging of the choice must occur after a button press, like so:要打印有意义的值,选择的记录必须在按下按钮后发生,如下所示:

 let playerChoice; function bindEventListeners() { const btns = document.querySelectorAll(".btn"); for (var i of btns) { (function(i) { i.addEventListener('click', function() { playerChoice = i.innerText; logChoice(); }); })(i); } } function logChoice() { console.log(playerChoice); } bindEventListeners();
 <button class="btn">one</button> <button class="btn">two</button>

Console.log() after you pressed the button, not before that Console.log()在你按下按钮之后,而不是之前

 function getPlayerChoice() { let playerChoice; const playerButtons = document.querySelectorAll(".btn");//get all buttons elements playerButtons.forEach((button) => { button.addEventListener('click', () => { //this code runs after you press a button playerChoice = button.innerText; console.log(playerChoice); }); }); } getPlayerChoice();//call function once, not on every button press
 <button class="btn">button1</button> <button class="btn">button2</button> <button class="btn">button3</button> <button class="btn">button4</button> <button class="btn">button5</button>

You don't see the playerChoice because you print it before a button is pressed.您看不到 playerChoice,因为您在按下按钮之前打印了它。 Split the function into two parts:将 function 拆分为两部分:

  • one to add event listeners to the buttons一种是将事件侦听器添加到按钮
  • one to get the playerChoice value一个获取 playerChoice 值

 const playerButtons = document.querySelectorAll(".btn"); const getScoreButton = document.getElementById("getScore"); let playerChoice; playerButtons.forEach(function(elem) { elem.addEventListener("click", function() { playerChoice = this.innerText; console.log('click:', playerChoice); }); }); getScoreButton.addEventListener("click", function() { console.log('get playerChoice:', playerChoice); });
 <button class="btn">Alpha</button> <button class="btn">Beta</button> <button class="btn">Gamma</button> <button class="btn">Delta</button> <br /> <br /> <button id="getScore">Get score</button> <span></span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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