[英]Need help using increments and displaying in a textbox
我们需要一个文本框,您输入一个数字,点击一个按钮,然后它会增加1
,同时保持在同一个文本框中。 这是我到目前为止的代码:
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
JavaScript的:
function btnIncrement_onclick() {
// get textbox and assign to a variable
var countTextbox = document.getElementById("txtCounter");
var txtCounterData = txtCounter.value;
var countTextbox.value = 0++;
}
如果有人可以向我解释如何做到这一点,而不仅仅是给我答案。 我不知道为什么我这么难过。
请尝试以下简单代码:
function btnIncrement_onclick() { //asign the textbox to variable var textbox = document.getElementById("txtCounter"); //Get the value of textbox and add 1 then update the textbox textbox.value = parseInt(textbox.value)+1; }
<form action=#> <p> Current Count...<input type="text" id="txtCounter" value="0"> </p> <p> <input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()"> <input type="reset"> </p> </form> <noscript>This website requires JavaScript to be enabled.</noscript>
希望这可以帮助。
在您的HTML中:
在你的html中你有一个onclick="btnIncrement_onclick()"
,这意味着每次点击都会触发你的功能。
在你的JS中:
function btnIncrement_onclick() {
// Named as countTextbox you input. sou we can use it later.
var countTextbox = document.getElementById("txtCounter");
// Get the current value attribute of it, initialy 0.
var txtCounterData = txtCounter.value;
// The line above is not being used. but you can check it with a console.log like this:
console.log(txtCounterData);
// Now you are calling again your input and changing his value attribute. this ++ means a increment. so we are increasing +1;
countTextbox.value++;
}
您应该阅读有关增量和运算符以及DOM的更多信息(通过id选择标记的方式,并再次选择其属性)。
抱歉没有找到一个很好的英文来源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.