[英]Javascript - cart only adds 1 item one even if 2 or 5 the item are buyed
我的腳本只有HTML和Javascript格式,我找不到問題所在。 我有一個html頁,其中包含8種產品,都具有相同的html樣式。 但是,當我單擊產品2或8時,它總是只列出列表中的第一個產品。 而且我無法弄清楚我需要做什么才能使其正常工作。 (腳本中的某些文本使用我的母語瑞典語)
HTML代碼
<div id="Tama">
<h2>TAMA</h2>
<img src="images/trummor/tama.jpg">
<br/>
<p>TAMA Superstar. </p>
<p>Pris: 25000 kr</p>
<hr style="border: 1px solid #000;">
<form name="order">
<input type="hidden" id="IDnumber" value="004">
<input type="hidden" id="pris" value="25000">
<input type="hidden" id="item" value="Tama Superstar">
Välj antal:
<input type="text" id="antal" value="1" name="antal" onChange="this.value=CKquantity(this.value)" style="width:30px;" maxlength="1"> |
<input type="button" value="Köp" onclick="addElement(this.form);">
</form>
<hr style="border: 1px solid #000;">
<p>
<a href="#drums" onclick="drums()">Tillbaka till produkter</a>
</p>
</div>
JavaScript購物車文件
// -- CHECK IF ANTAL IS A NUMBER -- //
function CKquantity(checkString) {
var strNewQuantity = "";
for ( i = 0; i < checkString.length; i++ ) {
ch = checkString.substring(i, i+1);
if ( (ch >= "0" && ch <= "9") || (ch == '.') )
strNewQuantity += ch;
}
if ( strNewQuantity.length < 1 )
strNewQuantity = "1";
return(strNewQuantity);
}
// -- ADD TO CART -- //
// still problem - only enter the first item on the list either you click on the
second or last product
function addElement(thisForm)
{
var itemId = document.getElementById('IDnumber').value
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value;
var pris = document.getElementById('pris').value;
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
var sum = antal * pris;
newElement.innerHTML = "("+itemId+") "+ antal + " x " + itemName + " - " + pris + " kr, Totalt: " + sum + " kr";
parent.appendChild(newElement);
}
JavaScript是區分大小寫的腳本語言,這意味着其關鍵字應以right-case
形式書寫。 您應該編寫function
而不是FUNCTION
。
嘗試這個:
function addElement()
{
var itemName = document.getElementById('item').innerHTML;
var antal = document.getElementById('antal').value; // 'value' not 'VALUE'
var parent = document.getElementById('cart');
var newElement = document.createElement('li');
newElement.setAttribute('class','item');
newElement.innerHTML = antal + " x " + itemName;
parent.appendChild(newElement);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.