首页 > 解决方案 > 无法使用 javascript 访问我的 html 部分中的动态 ID

问题描述

我知道一点javascript和jquery。在这段代码中,我创建了一个动态 id="nm{{product.id}"。`

<div class="row">
        {% for product in product_objects %}
        <div class="col-md-3">
          <div class="card">
            <img src="{{product.image}}" alt="" class="card-img-top">
            <div class="card-body">
              <div id="nm{{product.id}}" class="card-title">
                  {{ product.title }}
              </div>
              <div class="card-text">
                {{ product.price }} tk

              </div>
              <a href="/{{product.id}}" class="btn btn-warning" name="button">View</a>
              <button id="{{product.id}}" class="btn atc btn-warning" name="button">Add to cart</button>

            </div>

          </div>

        </div>
    {% endfor %}

  </div>`

这是我的js部分:

DisplayCart(cart);
    function DisplayCart(cart){
      //console.log(cart);
      var cartString = "";
      cartString += "<h5>This is your cart</h5>";
      var cartIndex=1;
      for(var x in cart){
      //console.log(x);
      cartString += cartIndex;
      cartString += document.getElementById("nm"+x).innerHTML + "Quantity"+ cart[x] +"</br>";
      cartIndex+=1;
    }
      $('[data-toggle="popover"]').popover();
      document.getElementById("cart").setAttribute('data-content',cartString);
    }

但控制台显示以下错误:未捕获的类型错误:无法读取 null 的属性“innerHTML” 我如何对 id 使用 innerHTML 功能?完整脚本:有我的购物车。购物车是一个 JSON 对象并使用 localStorage 来存储购物车。

<script type="text/javascript">
    //console.log("working");
    if(localStorage.getItem('cart')==null){
      var cart={};
    }
    else{
      cart=JSON.parse(localStorage.getItem('cart'));
    }
    $(document).on('click','.atc',function(){
      console.log("the atc button is clicked");
      var item_id = this.id.toString();
      console.log(item_id);
      if(cart[item_id] != undefined){
        cart[item_id]=cart[item_id]+1;
      }
      else{
        cart[item_id]=1;
      }
      //console.log(cart);
      localStorage.setItem('cart',JSON.stringify(cart));
      document.getElementById("cart").innerHTML = "Cart("+ Object.keys(cart).length+")";
      //console.log(Object.keys(cart).length);
    });
/*    $(function () {
    $('[data-toggle="popover"]').popover()
    document.getElementById("cart").setAttribute('data-content','<h5>This is your cart</h5>')
  });*/
    DisplayCart(cart);
    function DisplayCart(cart){
      //console.log(cart);
      var cartString = "";
      cartString += "<h5>This is your cart</h5>";
      var cartIndex=1;
      for(var x in cart){
      //console.log(x);
      cartString += cartIndex;
      cartString += document.getElementById("nm"+x).innerHTML + "Quantity"+ cart[x] +"</br>";
      cartIndex+=1;
    }
      $('[data-tog
      gle="popover"]').popover();
      document.getElementById("cart").setAttribute('data-content',cartString);
    }



  </script>

标签: javascripthtmljqueryshopping-cartpopover

解决方案


推荐阅读