Javascript 一段代码不工作

Javascript piece of code not working

我的 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);
    }
}

好吧,我们需要查看 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";
}