我的 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,但乍一看,我想说这是因为您试图在事件回调中设置事件绑定(bind),除非您设置了事件,否则不会调用该绑定(bind)绑定(bind)。您必须将它们握紧:
// 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";
}
关于Javascript 代码不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42033762/