我有下拉菜单,最后 2 个是价格和门票,然后进行计算并在选择时在屏幕上显示总金额。 它工作正常,尽管如果我将选择更改为不同的价格,总数不会更新。 同样的想法也适用于用户选择 4 个或更多票证并在屏幕上显示消息的部分。 我确定这很简单,但我似乎无法弄清楚。
我附上了一个Jsfiddle。
http://jsfiddle.net/Dwdqg/
function totalPrice(ticketCount,priceAmount)
{
if (tickets.selectedIndex != 0 && price.selectedIndex != 0) // if the price and tickets is not 0 or not selected
{
tickets.onchange = ticketCount; //when tickets is changed assign the index to var ticketCount
price.onchange = priceAmount;
var ticketCount = tickets.value; //get the value of ticketCount index
var priceAmount = price.value;
var totalPrice = (ticketCount * priceAmount);
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
}
if (ticketCount >= 4) // if ticketCount is 4 or more
{
totalPrice = totalPrice + 10; // add on 10 to the price
document.getElementById("totalPrice").innerHTML = ("Total Price £" + totalPrice);
document.getElementById("moreTickets").innerHTML = ("Buying four or more tickets will add an additional £10 fee.")
}
}
不会在更改处理程序中调用totalPrice
。
例如:
price.onchange = function()
// totalPrice needs to be called
}
你已经把它附在这里
<select name="tickets" id="tickets" onChange="totalPrice(tickets)" style="width:120px">
但是,这仅响应票证数量的更改。您尚未将其附加到其他元素。
另外 - 您的 onchange 仅触发一次,因为您在更改事件触发后使用 fillList
替换选项字段。您可以重新附加处理程序,也可以让它响应click
事件。
话虽如此 - 我不建议将处理程序附加为 HTML 属性,我建议清理您的代码以提高可读性。