繁体   English   中英

a内的总和值<input>每次我按下一个按钮

[英]Sum value within a <input> every time I press a button

1.问题

大家好

每次我按下按钮时,它必须将输入框中的值加 1

问题是每次我按下按钮而不是向值添加 +1 时,它都会将值连接起来,就像它是一个字符串一样

单击按钮 5 次后的预期结果:

5

实际发生了什么:

11111

2.代码

// the html
<button id="add-one">+</button>
<input type="text" value="" id="output-box"/>
// the javascript
document
  .getElementById("add-one")
  .addEventListener("click", function () {
    document.getElementById("output-box").value += parseInt(1);
  });

请帮忙:(

input.value将始终返回一个字符串。 因此,为了减去该值,您需要先将其转换为数字:

 const setup = () => { document.getElementById("add-one").addEventListener("click", () => { const outputBox = document.getElementById("output-box"); outputBox.value = +outputBox.value + 1; }); }; window.addEventListener('load', setup);
 <button id="add-one">+</button> <input type="number" id="output-box">

尝试:

// the javascript
document
  .getElementById("add-one")
  .addEventListener("click", function () {
    let el = document.getElementById("output-box");
    // let v = parseInt(el.value) // wrong
    // per comments @PaulRooney, instead when parsing empty string returns Nan
    // so instead use:
    let v = parseInt(el.value) || 0
    el.value = v + 1
    
  });

通过这种方式,您可以在加 1 之前将原始值解析为 int。

您的代码有两个问题。 首先,您一直在传递“1”而不增加。 第二个是因为您使用的是加法赋值运算符(+=) ,这是将您按顺序传递的值添加为<input type="text" value="" id="output-box"/>是字符串类型。 所以,试试这个代码。 这应该解决它。

 // the javascript let i = 1; document.getElementById("add-one").addEventListener("click", function () { document.getElementById("output-box").value = i++; });

暂无
暂无

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

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