这是我的JSP代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Order a PIZZA</title>
</head>
<body>
<b>SUBIR'S JUST IN PIZZA</b><br>
<i>All PIZZAs in just 30 minutes</i>
<div align="left">
Pizza=150/-<br>
Garlic Bread=60/-<br>
Soft drink=45/-<br>
Extra Cheese=45/-<br>
Tax=12.25%
</div>
<div align="right">
Name:
<input type="text"><br>
Number of Pizza:
<input type="text" id="pizza" onchange="pizza_calculate()"><br>
Number of Garlic breads:
<input type="text"><br>
Number of Soft drinks::
<input type="text"><br>
Number of Extra cheese:
<input type="text"><br>
Total:
<input type="text" id="total"><br>
Tax:
<input type="text"><br>
<input type="button" value="reload">
<input type="submit" value="submit">
<script type="text/javascript" src="evaluate.js"></script>
</div>
</body>
</html>
我的评价.JS javascript如下:
var price=0;
var tax=0;
var pizza=150;
var garlicBread=60;
var softdrink=45;
var extraCheese=45;
var pizza_total=0;
var softdrink_total=0;
function pizza_calculate()
{
var test=document.getElementById("pizza");
console.log(test);
pizza_total=document.getElementById("pizza")*pizza;
document.getElementById("total").innerHTML =pizza_total;
};
从Firebug我明白我的JS函数没有被执行。可能是这个错误的原因,请建议。
答案 0 :(得分:5)
这:
pizza_total=document.getElementById("pizza")*pizza;
应该是:
var pizza_total = parseInt( document.getElementById("pizza").value, 10) * pizza;
或者,因为您已将元素作为test
变量,只需:
var pizza_total = parseInt(test.value, 10) * pizza;
更新
var price = 0;
var tax = 0;
var pizza = 150;
var garlicBread = 60;
var softdrink = 45;
var extraCheese = 45;
var pizza_total = 0;
var softdrink_total = 0;
function pizza_calculate() {
var test = document.getElementById("pizza");
var pizza_total = parseInt(test.value, 10) * pizza;
document.getElementById("total").value = pizza_total;
};
<div align="right">
Name:
<input type="text">
<br>Number of Pizza:
<input type="text" id="pizza" onchange="pizza_calculate()">
<br>Number of Garlic breads:
<input type="text">
<br>Number of Soft drinks::
<input type="text">
<br>Number of Extra cheese:
<input type="text">
<br>Total:
<input type="text" id="total">
<br>Tax:
<input type="text">
<br>
<input type="button" value="reload">
<input type="submit" value="submit">
</div>
注意,如果您希望即时更新,可以使用onkeyup
代替onchange
。
答案 1 :(得分:4)
您只能使用ID Pizza获取DOMElement,而不是其值。尝试添加.value
以获取元素的值。像这样:
pizza_total= document.getElementById("pizza").value * pizza;
答案 2 :(得分:3)
其他人已经指出了您的脚本存在的一些问题,但是您的脚本未运行的原因是因为您有这样的问题:
<input type="text" id="pizza" onchange="pizza_calculate()"><br>
在html结束时加载脚本之前解析。
pizza_calculate
尚未定义。
将您的脚本移到顶部,或者更好,不要内联您的事件处理程序,而是使用addEventListener代替。
function pizza_calculate()
{
/* body of pizza_calculate */
}
var pizzaInput = document.getElementById("pizza");
pizzaInput.addEventListener("change", pizza_calculate, false);