我做的程序很简单,它没有任何数据库。我只是即兴创作并将每个产品的值放在按钮标签上。它工作得很好,但我遇到了一个问题。您可以操作数量的文本框仅适用于第一个数量文本框。例如,我首先更改第二个数量文本框的值,例如从初始值“1”更改为“3”,结果只显示我只添加了1个项目。从这个结果来看,我认为问题是我写的代码只是读取其他剩余数量文本框的初始值(除了第一个文本框)。所以基本上,我的问题是:如何在key up上更新文本框值并通知函数()它已被更新?
我的HTML:
<table border = "4" cellspacing = "3" cellpadding = "3" bgcolor = "white">
<col width = "250">
<col width = "400">
<col width = "200">
<col width = "200">
<col width = "200">
<tr>
<td align = "center"><h2 id = "item_name">product1</h2></td>
<td><b>Price :</b> <span id = "item_price" value = "17.10">$17.10</span><br>
<td><b>Quantity :</b> <input type = "text" value = "1" id = "quantity" onKeyUp="test();" style="width: 50px;"></td>
<td align = "center"><button value="17.10" name="product" id="button1" onclick="test(this);">Add to Cart</button></td>
</tr>
<tr>
<td align = "center"><h2 id = "item_name">product2</h2></td>
<td><b>Price :</b> <span id = "item_price" value = "39.00">$39.00</span><br>
<td><b>Quantity :</b> <input type = "text" value = "1" id = "quantity" onKeyUp="test();" style="width: 50px;"></td>
<td align = "center"><button value="39.00" name="product" id="button1" onclick="test(this);">Add to Cart</button></td>
</tr>
<tr>
<td align = "center"><h2 id = "item_name">product1</h2></td>
<td><b>Price :</b> <span id = "item_price" value = "49.00">$49.00</span><br>
<td><b>Quantity :</b> <input type = "text" value = "1" id = "quantity" onKeyUp="test();" style="width: 50px;"></td>
<td align = "center"><button value="49.00" name="product" id="button1" onclick="test(this);">Add to Cart</button></td>
</tr>
</table>
<table border = "0" cellspacing = "3" cellpadding = "3" bgcolor = "white" width = "700" align = "center">
<tr>
<td align = "center">Subtotal: <span id = "totaltext" value = "0">0</span>
(<span id="items" value = "0">0</span> items)</td>
</tr>
</table>
我的Javascript:
function test(button) {
var val = parseFloat(button.getAttribute("value"));
var quan = parseFloat(document.getElementById('quantity').value);
var total = parseFloat(document.getElementById('totaltext').getAttribute("value"));
var items = parseFloat(document.getElementById('items').getAttribute("value"));
if(button.getAttribute("name") === 'product')
document.getElementById('totaltext').innerHTML = total + val * quan;
document.getElementById('totaltext').setAttribute("value", total + val * quan);
document.getElementById('items').innerHTML = items + quan;
document.getElementById('items').setAttribute("value", items + quan);
}
P.S这是一个Jsfiddle https://jsfiddle.net/eLhsmq4p/(不知道为什么它不在那里工作)