jquery - 未捕获的类型错误:无法读取未定义的属性“innerHTML”,如果跨度文本为空
问题描述
如果跨度标记文本为空,我会收到此错误:Uncaught TypeError: Cannot read property 'innerHTML' of undefined
我不知道如何修复它。span 标签保存购物车中的数量值,它的作用是,如果数量值为 0,则整个产品将被删除。任何想法如何解决这个问题都非常感谢。
<td class="cart-qty" id="<?php echo $id ?>">
<div id="quantity">
<input class="addQty btn" type="button" value="+" id="<?php echo $id ?>" />
<span class="qty" id="<?php echo $id ?>"><?= $qty ?></span>
<input class="removeQty btn" type="button" value="-" id="<?php echo $id ?>" />
</div>
</td>
<td class="cart-price" id="<?php echo $id ?>">
<span id="<?php echo $id ?>"><?= $price * $qty ?></span>
<input type="hidden" name="priceTag" id="<?php echo $id ?>"
value="<?php echo $price ?>" />
</td>
$j(".removeQty").on("click", function(){
var id = $j(this).attr("id");
var quantity = $j(this).prev();
var qty = quantity.text();
var q = parseInt(qty);
var row = $j("table").find("[id='" + id + "']");
var action = "remove";
if(qty < 2) {
if(confirm("Are you sure you want to remove this product?")){
row.remove();
$j.ajax({
url:"http://localhost/wordpress/index.php/action/",
method:"POST",
data:{product_id:id, action:action},
success:function()
{
}
})
totalPrice();
}
else
{
return false;
}
} else {
quantity.text(--q);
}
subtractPriceByQty(id, qty);
totalPrice();
});
function subtractPriceByQty(id, qty) {
var cart_price_row = $j(".cart-price").find("[id='" + id + "']");
var cart_price_span = cart_price_row.eq(0)[0];
var cart_price = Number(cart_price_span.innerHTML);
var originalPrice = Number(cart_price_row.eq(1).val());
cart_price_span.innerHTML = parseFloat(cart_price-originalPrice).toFixed(2);
}
解决方案
如果没有更多上下文,这很困难,但我想您需要在删除最后一行时检查您是否仍有数据。所以也许这可以解决您的问题:
function subtractPriceByQty(id, qty) {
var cart_price_row = $j(".cart-price").find("[id='" + id + "']");
// Check that there is at least one row
if (cart_price_row.length) {
var cart_price_span = cart_price_row.eq(0)[0];
var cart_price = Number(cart_price_span.innerHTML);
var originalPrice = Number(cart_price_row.eq(1).val());
cart_price_span.innerHTML = parseFloat(cart_price-originalPrice).toFixed(2);
} else {
// Maybe we want to show '0.00' when there are no items
cart_price_span.innerHTML = '0.00';
}
推荐阅读
- sorting - 挑选出un arrayList的2个元素并按最高数字排序(JAVA)
- mysql - 在大型数据库 (~800G) 上使用 Google 数据库迁移服务复制失败,错误代码为 1062
- angular - FIREBASE 警告:使用未指定的索引。您的数据将在客户端下载和过滤
- python - MongoDB:如何在 MongoEngine Python Flask 中使用 $all 运算符
- python - ProcessPoolExecutor 工作人员具有相同的“线程 ID”?
- k-means - 如何为 kmeans 聚类在某些点设置初始质心?
- xml - xsd 验证失败 - 引用本地 xsd 文件
- powershell - 使用相同代码的 Powershell 5.1 和 Powershell 7 证书加密之间的区别
- typescript - TypeScript中基于字符串的类型条件参数
- ruby-on-rails - 有人可以提供一个带有多个图像的神社/铁轨示例吗?