我的javascript代码不起作用,它应该计算午餐菜单项的总价并给出总结果但是什么都没有出现。 html工作正常,所以我只是在这里编写javascript部分,它很简短。我按照指示来获取此代码,因此我没有弄错。谢谢:))
function calcTotal()
{
var itemTotal=0;
var items=document.getElementsByTagName("input");
//collects them into a NodeList object, which has indices
for(var i=0;i<5;i++)
{
if(items[i].checked)
itemTotal+=(items[i].value*1); //the *1 turns it into a number
}
document.getElementById("total").innerHTML="Your order total is $"+itemTotal + ".00";
var submitButton = document.getElementById("sButton");
if(submitButton.addEventListener)
{
submitButton.addEventListener("click",calcTotal,false);
}
else if(submitButton.attachEvent)
{
submitButton.attachEvent("onclick", calcTotal);
}
}
答案 0 :(得分:1)
好吧,我们需要看一下HTML,但乍一看,我说它是因为你试图在事件回调中设置事件绑定而不会被调用除非您已设置事件绑定。你必须把这些设置起来:
// First set up the event handling
var submitButton = document.getElementById("sButton");
// In this case, you can just check window to see if it has the property
if(window.addEventListener) {
submitButton.addEventListener("click",calcTotal,false);
} else if(window.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
// And, have the callback separate
function calcTotal() {
var itemTotal=0;
var items=document.getElementsByTagName("input");
//collects them into a NodeList object, which has indices
for(var i=0;i<5;i++) {
if(items[i].checked)
itemTotal+=(items[i].value*1); //the *1 turns it into a number
}
document.getElementById("total").innerHTML="Your order total is $"+itemTotal + ".00";
}