我正在尝试构建一个非常简单的Web应用程序.
我希望在按下按钮后存储一个文本字段的值,然后添加.
例如,如果我输入3,点击提交,然后5,点击提交,然后2,我希望结果为10,但我不知道如何做到这一点.
<style media="screen">
.error {
display: none;
}
.number {
display: none;
}
</style>
<body>
<form>
<label for="numberInput">Write a number: </label>
<input type="text" name="numberInput" class="numberInput" id="numberInput">
<button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
<div id="error" class="error">
</div>
<div id="number" class="number">
</div>
<script type="text/javascript">
$("#submitBtn").on("click", function() {
if ($("#numberInput").val() != "") {
$("#error").hide();
$("#error").text("");
var storedValue = $("#numberInput").val();
$("#number").show();
$("#number").text(storedValue);
} else {
$("#error").show();
$("#error").text("Please complete the above field.");
}
});
</script>
如果我输入5然后输入2,我希望结果为7,但是,显示的实际结果是2.
最佳答案 我只是略微更改了您的代码(所有更改都标有注释).
注意事项:
>如果将storedValue设为全局变量并将其初始化为0,则每次提交表单时都可以继续向其添加#numberInput值(并保留上一次提交的值).
注意:每次重新加载页面时,storedValue都将重置为0.
>您需要将numberInput值强制转换为int,否则它将被解释为字符串,并且您正在进行的数值计算将无法按预期工作.
另外,我没有在代码中看到表单的结束标记,所以我添加了它.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style media="screen">
.error {
display: none;
}
.number {
display: none;
}
</style>
<script src="jquery.min.js"></script>
</head>
<body>
<form>
<label for="numberInput">Write a number: </label>
<input type="text" name="numberInput" class="numberInput" id="numberInput">
<button type="button" name="submitBtn" class="submitBtn" id="submitBtn">Submit</button>
</form>
<div id="error" class="error">
</div>
<div id="number" class="number">
</div>
<script type="text/javascript">
//create a global variable so we can keep values stored from previous form submissions.
//initialize it to 0. Therefore everytime the page reloads the value will
//reset to 0.
var storedValue = 0;
$("#submitBtn").on("click", function() {
if ($("#numberInput").val() != "") {
$("#error").hide();
$("#error").text("");
//we need to cast the input value to an int otherwise it will be
//interpreted as a string.
//add the input value to the current storedValue.
storedValue = storedValue + parseInt($("#numberInput").val());
$("#number").show();
$("#number").text(storedValue);
} else {
$("#error").show();
$("#error").text("Please complete the above field.");
}
});
</script>
</body>
</html>