简体   繁体   English

如何正确使用for循环在按钮数组中添加onclick函数?

[英]How to add onclick functions in an array of buttons using a for loop properly?

I'm making a kind of HTML calculator to test something I have in mind. 我正在制作一种HTML计算器来测试我想到的东西。 I've used a for loop to create the buttons of the keypad. 我使用了for循环来创建键盘的按钮。 The display is a text field. 显示是一个文本字段。 Then I used a for loop to add the functions in the buttons: 然后,我使用了for循环将功能添加到按钮中:

for (var i = 0; i < 10; i++)
{
    buttons[i].onclick = function()
    {
        display.value += i;
    };
}

What I was trying to do is to make, for example, buttons[0] add "0" to the value of the text field when clicked. 我试图做的是例如使button [0]在单击时将“ 0”添加到文本字段的值。 Instead, clicking any button added "10" in the text field. 相反,单击任何按钮都会在文本字段中添加“ 10”。 Why? 为什么? How can I make it right? 我该怎么做?

You almost got it right , you just need to change var to let in your loop declaration : 你几乎得到它的权利,你只需要改变varlet你的循环声明:

 for (let i = 0; i < 10; i++)
{
    buttons[i].onclick = function()
    {
        display.value += i;
    };
}

What's the difference between using "let" and "var"? 使用“ let”和“ var”有什么区别? Here you can get more info about your issue. 在这里您可以获取有关您的问题的更多信息。

Your problem is that you are referencing i directly in your functions that you are binding to your Buttons. 您的问题是您直接在绑定到Button的函数中引用i i will actually continue to exist even after you bound all your events, and its value will be the last value of the iteration 10 . 即使绑定了所有事件, i实际上仍将继续存在,并且它的值将是迭代10的最后一个值。 So whenever a click function runs, it looks up i and finds the last value you set ( 10 ) and takes that value. 因此,每当单击函数运行时,它都会查找i并找到您设置的最后一个值( 10 )并采用该值。 What you want to do is add a constant reference instead - so that you bind that value you have during the loop and keep that reference forever, no matter how i might change later. 你想要做的是增加一个恒定的引用,而不是-让您绑定的循环过程中,你有一个价值,并保持该基准永远,无论怎样i可能会在以后更改。

for (var i = 0; i < 3; i++) {
    const localValue = i
    buttons[i].onclick = function()
    {
        counter += localValue;
        counterElement.innerHTML = counter
    };
}

I created a small example fiddle here: https://jsfiddle.net/4k8cds9n/ if you run this you should see the buttons in action. 我在此处创建了一个小示例提琴: https : //jsfiddle.net/4k8cds9n/如果运行该提琴,您应该会看到按钮的作用。 Some related reading for this topic would be around scopes in javascript, one good article: https://scotch.io/tutorials/understanding-scope-in-javascript 与该主题相关的一些阅读将围绕javascript的范围进行,一篇不错的文章: https : //scotch.io/tutorials/understanding-scope-in​​-javascript

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

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