我试图通过javascript制作一个简单的计算器,而且我没有得到任何文本框结果。
<html>
<head>
<script type="text/javascript">
function sum()
{
var x1 = document.getElementById("text1");
var x2 = document.getElementById("text2");
var y = document.getElementById("text3");
var sum = parseFloat(x1) + parseFloat(x2);
y.value = "the result is, " + sum;
}
</script>
</head>
<body>
<form>
<fieldset style="width : 100px ;text-align: center; margin-left: auto;margin-right: auto;">
<legend> sum +++ +++ calculator</legend>
<input type="text" placeholder="tap first number" id="text1"><br>
<input type="text" placeholder="tap second number" id="text2"><br>
<input type="button" value="=" onclick="sum()"><br>
<input type="text" placeholder="result" id="text3"><br>
</fieldset>
</form>
</body>
</html>
答案 0 :(得分:2)
您的x1和x2是指输入框而不是值。改为:
var x1 = document.getElementById("text1").value;
var x2 = document.getElementById("text2").value;
答案 1 :(得分:1)
原因是你永远不会从文本字段中获取值。
检查以下内容:
function sum() {
var x1 = document.getElementById("text1");
var x2 = document.getElementById("text2");
var y = document.getElementById("text3");
var sum = parseFloat(x1.value) + parseFloat(x2.value);
y.value = "the result is, " + sum;
}
<form>
<fieldset style="width : 100px ;text-align: center; margin-left: auto;margin-right: auto;">
<legend> sum +++ +++ calculator</legend>
<input type="text" placeholder="tap first number" id="text1">
<br>
<input type="text" placeholder="tap second number" id="text2">
<br>
<input type="button" value="=" onclick="sum()">
<br>
<input type="text" placeholder="result" id="text3">
<br>
</fieldset>
</form>
希望它对你有所帮助。 谢谢!
答案 2 :(得分:0)
<html>
<head>
<script type="text/javascript">
function sum()
{
var x1 = document.getElementById("text1");
var x2 = document.getElementById("text2");
var y = document.getElementById("text3");
var sum = parseFloat(x1.value) + parseFloat(x2.value);
y.value = "the result is, " + sum;
}
</script>
</head>
<body>
<form>
<fieldset style="width : 100px ;text-align: center; margin-left: auto;margin-right: auto;">
<legend> sum +++ +++ calculator</legend>
<input type="text" placeholder="tap first number" id="text1"><br>
<input type="text" placeholder="tap second number" id="text2"><br>
<input type="button" value="=" onclick="sum()"><br>
<input type="text" placeholder="result" id="text3"><br>
</fieldset>
</form>
</body>
</html>