首页 > 解决方案 > 未捕获的类型错误:无法读取未定义的属性“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);
        }

标签: jqueryajax

解决方案


如果没有更多上下文,这很困难,但我想您需要在删除最后一行时检查您是否仍有数据。所以也许这可以解决您的问题:

   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';
  }

推荐阅读