根据 Javascript 中的输入计算面积
我这里有一个非常简单的 JavaScript 计算器,但它似乎不起作用。我确信这是一个非常容易解决的问题,但只是看不到它。我花了一段时间思考这个问题,并认为我最好在这里问。有什么建议吗?谢谢! http://jsfiddle.net/z98gb/7/
Width <input type="Text" name="width" size="4">
Height <input type="Text" name="height" size="4" onkeyup=""> <br><br>
Area <input type="Text" name="area" id="area" size="4"> <br><br>
<input type="button" name="calculate" id="area" size="4" onclick="calculateArea()" value="calculate">
这是 JavaScript:
function calculateArea() {
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var area = width * height;
document.getElementById("area").value = area;
}
I've got a very simple javascript calculator here but it doesn't seem to be working. I'm sure it's something very simple to solve but just can't see it. I've spent a while on it and thought I'd be better off asking here. Any suggestions? Thanks! http://jsfiddle.net/z98gb/7/
Width <input type="Text" name="width" size="4">
Height <input type="Text" name="height" size="4" onkeyup=""> <br><br>
Area <input type="Text" name="area" id="area" size="4"> <br><br>
<input type="button" name="calculate" id="area" size="4" onclick="calculateArea()" value="calculate">
And here's the javascript:
function calculateArea() {
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var area = width * height;
document.getElementById("area").value = area;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有为输入指定 id
工作示例: http://jsfiddle.net/z98gb/8/< /a>
You didn't specify an id for your input
Working example : http://jsfiddle.net/z98gb/8/
在执行计算之前,您需要将 DOM 值转换为实际数字。如果您要处理整数,请使用
parseInt
,或者更有可能的是,使用parseFloat
来支持小数。如果您使用
parseInt
,请不要忘记指定 10 来表示基数 10。否则将导致 JavaScript 将前导零视为基数 8。编辑
,您忘记在输入中添加 ID。
You need to convert your DOM values to actual numbers before performing calculations on them. Use
parseInt
if you're working with whole numbers, or, more likely, useparseFloat
to support decimals.If you use
parseInt
, don't forget to specify a 10 to signify base 10. Failure to do so will cause JavaScript to treat leading zeroes as though they were in base 8.EDIT
Also, as Francis notes, you forgot to add IDs to your inputs.
您使用的是 getElementById 而不是 getElementByName。您需要指定一个 id 或切换您在代码中使用的内容。
You're using getElementById and not getElementByName. You either need to specify an id or switch what you use in your code.