지난 며칠 동안 나는 자바 스크립트를 머리에 쓰려고 노력했다. 이것은 내 첫 번째 적절한 자바 스크립트이며 누구나 내가 내 코드를 개선하고 궁극적으로 자바에 대한 지식을 향상시킬 수 있는지 궁금해하고 있습니다. 지금까지는 내 코드가 고맙겠습니다.Javascript 장바구니 코드를 개선하려면 어떻게해야합니까? 원시 코드를 용서하십시오.
내가 'calcUnitPriceF'함수를 완료하는 방법에 난처한 점이있어서 각 제품 케이스에 배열을 만들지 않습니다. 이 가격은 곧 데이터베이스에서 나올 것입니다.
아래 코드는 그것이하는 일이 매우 분명하기를 바랍니다.
<script type="text/javascript">
function update(){
var total = 0.00;
var calcUnitPrice, quantity;
var myForm = document["getElementById"]("totalform");
var justQuantity = myForm["quantity[]"];
var justPrice = myForm["productPrice[]"];
var unitPrice = myForm["unitPrice[]"];
var linePrice = myForm["linePrice[]"];
for(var i =0; i < justQuantity.length; i++)
{
justQuantity[i].value = Math.floor(justQuantity[i].value);
quantity = justQuantity[i].value;
calcUnitPrice = 0;
if(isNaN(quantity) || quantity < 0) {
justQuantity[i].value ="0";
}
else
{
calcUnitPrice = calcUnitPriceF(justPrice[i].value,quantity);
document.getElementById('unitPrice[' + i + ']').innerHTML = '£' + calcUnitPrice.toFixed(2);
document.getElementById('linePrice[' + i + ']').innerHTML = '£' + (calcUnitPrice * justQuantity[i].value).toFixed(2);
total = (total + (quantity* calcUnitPrice));
}
}
document.getElementById("delivery").innerHTML = "Your Order Delivery is: £2.50";
document.getElementById("Totprice2").innerHTML = "Your Order Total is: £" + total.toFixed(2);
}
function calcUnitPriceF(product,quantity)
{
switch(product)
{
case '0':
return 0;
case '1':
var values = [5, 4 , 15.30 , 10 , 12 ]; // Structure(Exceeding Quantity Price,Quantity Under, Price)
for(var i = 1; i< values.length; i=i+2)
if(quantity < values[i])
return values[i+1];
return values[0];
case '2':
return 75;
}
}
</script>
<body>
<form id="totalform">
<select id ="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[0]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[0]" style="display:inline;">£0.00</p><br />
<select id="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[1]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[1]" style="display:inline;">£0.00</p><br />
<span id ="delivery">Your Order Delivery is: £0.00</span><br />
<span id ="Totprice2">Your Order Total is: £0.00</span>
</form>
장바구니에 제품 라인이 1 개 (HTML 블록 한 개) 밖에 없다면 작동하지 않습니다. –
개선을 정의하십시오. 여러 가지 방법으로 코드를 개선 할 수 있습니다 (예 : 당신은 인간의 판독 가능성이나 수행 능력을 향상시킬 수 있습니다. – Raoul
개선 사항 정의 : Javascript 기술을 향상시킬 수있는 부분을 확인하십시오. 내가 말했듯이 이것은 Javascript에서 시도한 첫 번째 시도이며 개선하기를 원한다. –