请原谅协议和/或格式化方面的任何潜在失误。我是新来的。单击我的“提交”按钮不会调用函数cost()。我做错了什么?
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg");
distance = document.getElementById("distance");
gasPrice = document.getElementById("gasPrice");
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<h1>Trip Cost Calculator</h1>
</head>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg">
</input>
</body>
<body>
<p> Enter distance (miles): </p>
<input type="text" id="distance">
</input>
</body>
<body>
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice">
</input>
</body>
<body>
</br>
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>
答案 0 :(得分:1)
你正在操纵对象。使用像这样的值属性来恢复值。
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
答案 1 :(得分:1)
你需要这些元素的价值,而不是它自己的元素:
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert(Math.round((distance / mpg) * gasPrice));
}
</script>
您还需要删除所有额外的<body>
代码。
答案 2 :(得分:0)
您的身体标签不正确。您还需要关闭html
标记。此外,使用.value
属性访问input
字段。
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<h1>Trip Cost Calculator</h1>
</head>
<body>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg">
</input>
<p> Enter distance (miles): </p>
<input type="text" id="distance">
</input>
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice">
</input>
</br>
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>
</html>
答案 3 :(得分:0)
此处各种级别的问题出错,首先是确保您拥有有效的HTML 。使用DOM节点时,最好确保您的浏览器可以创建有效的dom树,并且最适合使用有效的html。查看http://validator.w3.org
其次,在您的cost()
函数中,您没有获取输入字段的值,而是自己获取字段。当然,这会导致一些奇怪的行为,这可能会解释你认为cost()函数没有被执行。它可能只是抛出你没注意到的错误(检查浏览器的调试/错误控制台)
我修复了你的例子,检查它,从中学习并阅读webstandards:)
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function cost() {
mpg = document.getElementById("mpg").value;
distance = document.getElementById("distance").value;
gasPrice = document.getElementById("gasPrice").value;
alert("<p>" + Math.round((distance / mpg) * gasPrice) + "</p>");
}
</script>
<title>Trip cost calculator</title>
</head>
<body>
<h1>Trip Cost Calculator</h1>
<p> Enter mpg (miles): </p>
<input type="text" id="mpg" />
<p> Enter distance (miles): </p>
<input type="text" id="distance" />
<p> Enter gas price (dollars): </p>
<input type="text" id="gasPrice" />
<input type="button" id="submit" value="Submit" onclick="cost()"/>
</body>