2016-10-08 29 views
-1

我想製作一個基本的購物車應用程序,您可以在其中點擊項目,每次點擊都應該添加項目到一個數組。最後,您應該可以按下一個總按鈕並查看所有已添加的項目,但目前爲止它無法使用。使用array.push的基本購物車();

到目前爲止的代碼:

function add() { 

var shoppingCart = []; 

document.getElementById("itemOne").addEventListener("click", function() { 
shoppingCart.push("One"); 
    }); 

document.getElementById("itemTwo").addEventListener("click", function() { 
    shoppingCart.push("Two") 
    }); 

document.getElementById("total").addEvenetListener("click", function() { 

document.getElementById("display").innerHTML = 
    shoppingCart; 
}) 
} 

的jsfiddle:https://jsfiddle.net/xpb8oarx/

+0

定義_「它不工作」_!你能分享可執行的演示/片段或[JSFiddle](https://jsfiddle.net/)嗎? [_創建一個最小,完整和可驗證的示例_](http://stackoverflow.com/help/mcve) – Rayon

+0

編輯原創並添加了JSFiddle。 – Sergi

+0

你永遠不會調用函數'add()',它包含一個錯字。 – Thomas

回答

2
  • 錯字@addEventListener
  • 從來沒有所謂的add()你不需要說反正

var shoppingCart = []; 
 
document.getElementById("itemOne").addEventListener("click", function() { 
 
    shoppingCart.push("One"); 
 
}); 
 

 
document.getElementById("itemTwo").addEventListener("click", function() { 
 
    shoppingCart.push("Two"); 
 
}); 
 

 
document.getElementById("total").addEventListener("click", function() { 
 
    document.getElementById("display").innerHTML = shoppingCart; 
 
});
.container { 
 
    width: 70%; 
 
    background-color: black; 
 
    height: 300px; 
 
    margin: 0 auto; 
 
} 
 
#itemOne, 
 
#itemTwo { 
 
    width: 100px; 
 
    height: 100px; 
 
    border: 1px solid white; 
 
    margin: 1%; 
 
    color: white; 
 
} 
 
#display { 
 
    color: white; 
 
    text-align: center; 
 
}
<div class="container"> 
 

 
    <div id="itemOne" class="itemOne"> 
 
    <button class=" item">Chicken</button> 
 
    </div> 
 

 
    <div id="itemTwo"> 
 
    <button class="item">Veggies</button> 
 
    </div> 
 

 
    <button id="total">Total</button> 
 
    <h1 id="display"></h1> 
 
</div>

+0

當它允許我接受答案時,它按預期工作,謝謝。 – Sergi

0

你會找到一個教程HERE解釋如何實現純HTML5和香草車。 由法國JS忍者寫的Tuto