我是否应该将所有这些都放在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>
您只需要将任何getElement
调用或对获取元素的函数的调用放在load函数中。
好吧,你可以,但那可能会延迟一些js代码从开始工作的部分。html代码首先被加载。它还使代码缩进过多,导致可读性问题。