2013-03-04 2 views
-3

지난 며칠 동안 나는 자바 스크립트를 머리에 쓰려고 노력했다. 이것은 내 첫 번째 적절한 자바 스크립트이며 누구나 내가 내 코드를 개선하고 궁극적으로 자바에 대한 지식을 향상시킬 수 있는지 궁금해하고 있습니다. 지금까지는 내 코드가 고맙겠습니다.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> 
+0

장바구니에 제품 라인이 1 개 (HTML 블록 한 개) 밖에 없다면 작동하지 않습니다. –

+0

개선을 정의하십시오. 여러 가지 방법으로 코드를 개선 할 수 있습니다 (예 : 당신은 인간의 판독 가능성이나 수행 능력을 향상시킬 수 있습니다. – Raoul

+0

개선 사항 정의 : Javascript 기술을 향상시킬 수있는 부분을 확인하십시오. 내가 말했듯이 이것은 Javascript에서 시도한 첫 번째 시도이며 개선하기를 원한다. –

답변

1

내가 할 수있는 한 가지는 JS 방식을 변경하는 것입니다.

var project = {}; 
project.ShoppingCart = function() { 
    this.total = 0; 
    this.justQuantity = ...; 
    this.currentQuantity = 0; 
}; 
/** 
* Updates the current quantity in the shopping cart. 
* @param {!number} quantity The quantity to update with. 
* @return {void} nothing. 
*/ 
project.ShoppingCart.prototype.updateQuantity = function(quantity) { 
    // this is how to check for a number properly. 
    if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity)) { 
     this.currentQuantity = quantity; 
    } else { 
     console.log("Invalid quantity"); 
    }; 
}; 

이제 위의 내용을 사용하십시오. 객체에서

var shoppingCart = new project.ShoppingCart(); 

봐 자바 스크립트가 제대로 그것을 사용하는 방법, 글로벌 네임 스페이스를 poluting 무작위 함수를 작성 중지 지향을, 코드를 언급하고 제대로 일을 확인합니다.

+0

이 방향으로 나를 가르쳐 주셔서 감사합니다. 나는 지금이 길을 택할 것이다. 이게 과도하지 않은가? 제가하고 싶은 것은 제가 달성 한 것입니다 : 제품의 가격 업데이트 및 delievery/total. –

+0

감사합니다. 나는 당신에게 정직한 좋은 JS 리소스를 찾지 못했습니다. 나는 야후를 만든 사람의 비디오를 보는 것에 의지했다. 그러나 나는 그것을보고 배우는 것보다 읽기 쉽고 배우기가 훨씬 쉽습니다. 나는 w3schools로 넘겨주는 경향이 있지만 아주 기본적인 것이다. 나는 제 6 판 Orielly 책을 가지고 있는데, 나는 그것을 씹을 것이다. –

관련 문제