简体   繁体   English

在 JS 中无法正确重置的重置按钮

[英]reset button that won't reset properly in JS

I've created 3 buttons, when you push one of them, indicates how many times you have clicked on that button.我创建了 3 个按钮,当您按下其中一个时,会指示您单击该按钮的次数。

I succeeded in making the button work properly.我成功地使按钮正常工作。 But the reset button I made is broken, which is the issue.但是我做的重置按钮坏了,这就是问题所在。

when you click the rest button it's going to '0' but after starting the button press again counting starts from '2' or '3', not from the number '1'.当您单击 rest 按钮时,它将变为“0”,但在启动按钮后再次按下计数从“2”或“3”开始,而不是从数字“1”开始。

please help me to sort this matter.请帮我解决这个问题。

 let btns=document.querySelectorAll('.box'); let reset=document.getElementById('rest'); btns.forEach(btn => { btn.addEventListener('click', () => { btn.innerText= ++ btn.value; }); }); reset.addEventListener('click', ()=>{ btns.forEach(btn => { btn.innerText= 0; }); });
 button{ height: 100px; width: 100px; }
 <button class="box" value="0">0</button> <button class="box" value="0">0</button> <button class="box" value="0">0</button> <button id="rest">Reset</button>

get the innerText and then add 1 to it per click.获取innerText ,然后每次点击添加 1 。

  1. You're getting the value of the button, but are never setting it你得到了按钮的价值,但从来没有设置它

  2. You're not parsing the value as an int.您没有将值解析为 int。 You can't use ++ or calculating functions on strings, but getting a value or text from an element always returns a string type, not an integer.您不能对字符串使用 ++ 或计算函数,但从元素中获取值或文本始终返回字符串类型,而不是 integer。

let btns=document.querySelectorAll('.box');
let reset=document.getElementById('rest');


    btns.forEach(btn => {   
        btn.addEventListener('click', () => {
                btn.innerText= parseInt(btn.innerText) + 1;
        });
});


reset.addEventListener('click', ()=>{
        btns.forEach(btn => {
                btn.innerText= 0;
        });     
       
});

Thanks to NoobishPro感谢 NoobishPro

You are setting the btn text to 0 when reset.重置时将 btn 文本设置为 0。 You also have to set the button value to 0. Which you are incrementing.您还必须将按钮值设置为 0。您正在递增。 As result when you reset only text is changed, value reamains the same.结果,当您重置时,仅更改文本,值保持不变。

let btns = document.querySelectorAll('.box')
let reset = document.getElementById('rest')

btns.forEach(btn => {   
  btn.addEventListener('click', () => {
    btn.innerText = parseInt(btn.innerText) + 1
  })
})


reset.addEventListener('click', () => {
  btns.forEach(btn => {
    btn.innerText = 0
    btn.value = 0
  })
})

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

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