addEventListener回调未从元素值的更改?

英文:

Trying to create a button that update the H1 number based on how many times I pressed it. And I added a select element to select the maximun number H1 can go to.
Why does it not work when I define the playRounds variable outside of the addeventlistener call back. but works when I define it in the callback.
this works:

const h1 = document.querySelector("h1");
const roundsToPlay = document.querySelector("select");
const button = document.querySelector("button");

let buttonPressNumber = 0;

button.addEventListener("click", () => {
    let playRounds = roundsToPlay.value
    if (buttonPressNumber < playRounds) {
        buttonPressNumber += 1;
        h1.innerText = buttonPressNumber;
    }
})

this Does not work:

const h1 = document.querySelector("h1");
const roundsToPlay = document.querySelector("select");
const button = document.querySelector("button");

let buttonPressNumber = 0;
let playRounds = roundsToPlay.value

button.addEventListener("click", () => {

    if (buttonPressNumber < playRounds) {
        buttonPressNumber += 1;
        h1.innerText = buttonPressNumber;
    }

})

When I define the "playRounds" varaible equals to an acutal number outside of the callback, it works too. So it shouldn't be a scope problem.
eg:
let playRounds = 5;

Does the callback in addEventListner not take updates from the change of value in <select> element when it's defined outside of the callback?

答案1

得分: 1

当你执行 let playRounds = roundsToPlay.value 时,value(例如,"4")会从 roundsToPlay.value 复制到 playRounds,但之后 roundsToPlay.valueplayRounds 之间不会保持连接。JavaScript 不支持对变量或对象属性的引用(除了在规范内概念上有,但这与你编写的代码无关,只与规范的书写方式相关)。

如果你想获取最新的值,你需要在事件处理程序中像在你的示例中那样检索它。

英文:

When you do let playRounds = roundsToPlay.value, the value (for instance, "4") is copied from roundsToPlay.value to playRounds, but there is no ongoing connection between roundsToPlay.value and playRounds afterward. JavaScript does not have references to variables or object properties (other than conceptually within the specification, but that isn't relevant to the code you write, just how the specification is written).

If you want the up-to-date value, you have to retrieve it in the event handler as you do in your working example.

答案2

得分: 0

playRounds只被赋值一次,所以如果你的<select>中的第一个&lt;option&gt;1,那么playRounds将永远为1,因为它从未被更新。

相反,你需要将buttonPressNumber与当前的roundsToPlayvalue进行比较。


    if (buttonPressNumber &lt; roundsToPlay.value) {
        buttonPressNumber += 1;
        h1.innerText = buttonPressNumber;
    }

})

https://jsfiddle.net/vzw6e9my/1/

英文:

playRounds is only assigned once, so assuming the first &lt;option&gt; in your &lt;select&gt; is 1 then playRounds will be 1 forever as it's never updated.

Instead you need to compare buttonPressNumber to the current value of roundsToPlay


    if (buttonPressNumber &lt; roundsToPlay.value) {
        buttonPressNumber += 1;
        h1.innerText = buttonPressNumber;
    }

})

https://jsfiddle.net/vzw6e9my/1/