[英]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.