我正在尝试创建一个循环以在我的结帐页面上显示购物车总额。我试图在循环中创建一些数组变量来保存我的值,但控制台给了我一个“ 意外的错误。 *附加到“ p”和“ q”的“ i”值是指我的购物车表中所显示产品的ID。
购物车表代码:
<?php
$query = "select * from tbl_cart WHERE
member_id= '$member_id'";
$result = mysqli_query($conn,$query);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
echo "<table id='anyclass'>";
echo "<tr>
<th style= border-right-style:none;
id='image1'></th>
<th style= text-align: center;
border-left-style:none;
id='product1'>Product</th>
<th id='price1'>Price</th>
<th id='quantity1'>Quantity</th>
<th id='remove1'>Remove</th>
</tr>";
$i=1;
while($row = $result->fetch_assoc()) {
echo "<tr class= 'trhide'>";
echo '<td style=border-right-
style:none;><img src="' . $row['image']
. '" /></td>';
echo "<td style=border-left-
style:none;
id='product'>".$row['product_id']."</td>";
echo "<td style= 'text-align: right;' id=
'p$i' >".$row['price']."
</td>";
echo "<td id= 'quantity' >". "
<input id= 'q$i' style='border:none'
type = 'text' class= 'change' value=
$row[quantity] name= $row[id] data-id=
$row[id]
>" . "</td>";
echo "<td id= 'delete'><span
class='delete' data-id= $row[id] ><img
src=delete.svg></span></td>";
echo "<td id= 'o$i' >".$row['oz']."
</td>";
echo "</tr>";
$i++;
}
echo "<tr>
<td>Total:</td>
<td id= 'total'></td>
</tr>";
echo "</table>";
?>
<script>
var total0=0;
var sum=0;
var i;
for (i = 1; i < 1000; i++) {
if(document.getElementById("p"+i)==null){
var p[i]= 0;
}
else{varp[i]=parseFloat
(document.getElementById
('p'+i).innerText)*100;}
if(document.getElementById('q'+i)==null){
var q[i]= 0;
}
else{var q[i]=
document.getElementById('q'+i).value;
}
var total[i]= parseInt(p[i]) *
parseInt(q[i]);
var sum= sum + total[i];
}
window.alert(sum);
</script>
答案 0 :(得分:0)
我不确定这是否是好的代码,但是它对我有用,并解决了我的问题。
<script>
var total0=0;
var sum=0;
var i;
var q = new Array();
var p = new Array();
var total = new Array();
for (i = 1; i < 1000; i++) {
if(document.getElementById("p"+i)==null){
p[i]= 0;
}
else{p[i]=parseFloat(document.getElementById('p'+i)
.innerText)*100;
}
if(document.getElementById('q'+i)==null){
q[i]= 0;
}
else{q[i]= document.getElementById('q'+i).value;
}
total[i]= parseInt(p[i]) * parseInt(q[i]);
var sum= sum + total[i];
}
var result= sum/100;
document.getElementById('total').innerHTML = '$' +
result;