0

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

1 回答 1

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";
}
于 2017-02-03T22:10:58.130 回答