Ani*_*ukh 5 html database jquery dom
我有这个表从数据库加载,所以所有元素each row都具有相同的属性.
<table class="table table-responsive">
<tr>
<th>Product name</th>
<th>Quantity</th>
<th>Price per unit</th>
<th>Total</th>
<th>Action</th>
</tr>
<tr>
<td class="product-name">Product one name</td>
<td class="product-quantity">
<!-- plus button should increase quantity and update total based on unit_price*quantity -->
<button class="btn"> +</button>
<input type="text" value="2"/>
<button class="btn"> -</button>
</td>
<td class="unit-price">50</td>
<td class="total-price">100</td>
<td>
<!-- this should delete entire row -->
<button class="product-delete">Delete</button>
</td>
</tr>
...
</table>
<!-- on each quantity change this needs to update -->
<div class="grand-total"> 5000 </div>
Run Code Online (Sandbox Code Playgroud)
我试图制作jQuery但无法解决,因为每一行都有相同的属性我无法选择特定的行并更新它的内容以使其工作.
我搜索了很多,但我找到的只是基于id和类选择器的HTML操作,我不能使用,因为每行的元素都有相同的类,我不能给每个元素赋予唯一的id,因为它们从数据库加载(PHP ).
如果有人能告诉我如何做到这一点,我真的很感激jQuery.请不要给我链接到静态HTML操作使用jQuery我想要一个动态的解决方案HTML elements.
更新:这是工作示例:Fiddle example ,代码是:
$('.btn, .product-delete').on("click", function(){
$this=$(this);
var unitPrice=parseInt($this.parents("tr").find(".unit-price").text());
switch($this.text()){
case " +":
currentVal= parseInt($this.parents("tr").find("input[type='text']").val());
newVal=currentVal+1;
$this.parents("tr").find("input[type='text']").val(newVal);
$this.parents("tr").find(".total-price").text(unitPrice*newVal);
break;
case " -":
currentVal= parseInt($this.parents("tr").find("input[type='text']").val());
if(currentVal==0){
break;
}
newVal=currentVal-1;
$this.parents("tr").find("input[type='text']").val(newVal);
$this.parents("tr").find(".total-price").text(unitPrice*newVal);
break;
case "Delete":
$this.parents("tr").remove();
}
//sum all total cols
var total=0;
$(".total-price").each(function(){
total+= parseInt($(this).text());
});
$(".grand-total").text("Total "+total);
});
Run Code Online (Sandbox Code Playgroud)