我是否应该将所有这些放在 load() 正文事件中,以便在页面呈现并创建 DOM 对象后加载?(我确实发现我必须使用 .innerhtml 而不是 .value 才能工作。)如果是这样,如何...
(*我知道这是垃圾代码,但它比我上次的尝试好,比我的下一次尝试更糟糕。一旦我有时间回到这个问题,我将使用带有内部函数的文字构造函数重新创建它。我不希望在功能上进一步使用这个 Javascript。我拥有的后端 php 将处理安全和检查)
<script type="text/javascript">
//To get the price of a product applying discount
function getPrice(location,quantity)
{
//Get the product choice
var e = document.getElementById("productList["+location+"]");
var productSelected = e.options[e.selectedIndex].value;
//TODO: Determine discounts based on product choice
switch(productSelected)
{
case '0':
return 0;
case '1':
return 10;
case '2':
return 15;
}
return null;
}
//To update product only
function updateProduct(location)
{
updateRow(location,document.getElementById("quantity["+location+"]").value);
}
//To update only that row
function updateRow(location,quantity)
{
//Check Quantity is a valid Number and also not a float or negative
if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity) && (quantity >= 0)) {
quantity = Math.floor(quantity);
} else {
quantity = 0;
};
//Update the quantity input field to whatever quantity is - Investigate later!
document.getElementById("quantity["+location+"]").value = quantity;
//Store old Price for changing total
var oldTotal = document.getElementById("totalPrice").innerHTML;
var oldLinePrice = document.getElementById("linePrice["+location+"]").innerHTML;
//Calculate and Store Prices to adjust the total
var productPrice = getPrice(location,quantity).toFixed(2);
var newLinePrice = (quantity*productPrice).toFixed(2);
//Apply Updates
document.getElementById("unitPrice["+location+"]").innerHTML = productPrice;
document.getElementById("linePrice["+location+"]").innerHTML = newLinePrice;
document.getElementById("totalPrice").innerHTML = (oldTotal-oldLinePrice+parseFloat(newLinePrice)).toFixed(2);
}
</script>