1

我正在构建一个菜单订购应用程序,我必须在其中使用 Jquery。

我正在使用该clone()方法复制带有弹出必要数据的购物车项目。它工作一次,然后记录并object<prototype>.

我正在克隆的是我的 HTML 中的一个部分,我将其用作模板并id隐藏它。我在克隆的项目上删除了这个。

弹出我排除的数据,因为它工作正常并且功能在其他文件中,但我对它们是原因的想法持开放态度。

HTML:

        <div class="cart-item" id="cartitem-template">

          <div class="left">
            <div class="image"></div>
            <div class="price"></div>
          </div>

          <div class="mid">
            <div class="name">

            </div>
            <div class="stars">
              <span></span>
            </div>
            <div class="underline"></div>
            <div class="toggleReviews">
              <span></span>
            </div>
          </div>

          <div class="right">
            <div class="remove-cart-item">✕&lt;/div>
          </div>

        </div>

      </div>

JS函数:

    buildCartItem = function(menuItem) {
        const template = $("#cartitem-template")

        template
            .removeAttr("id")
            .clone(false)

        const newCartItem = template
        newCartItem.insertAfter(".cart-item")
        console.log(newCartItem)

        //Get object and index atts from clicked menu item
        //Also set that same data into the dom of the cart item
        //As well as set that data to local storage

        ...

        // Apply data to the cloned cart item template
        newCartItem.find(".image").css("background-image", "url(" + data.image + ")")
        setData(".price", "$"+data.price, newCartItem)
        ...
    }

    $(".menu-item").click(function() {
        buildCartItem($(this))
    })

我使用.clone()正确吗?老实说卡住了

4

2 回答 2

3

您甚至在克隆之前就从源元素中删除了属性“id”,这就是为什么在随后的方法调用中它无法找到 id 为“cartitem-template”的元素。因此,在您的方法 buildCartItem 中,克隆后删除“id”。

const newCartItem = template.clone(false).removeAttr("id");
于 2019-09-27T05:04:38.120 回答
1

var buildCartItem = function(menuItem) {
  const newCartItem = $("#cartitem-template").clone(false).removeAttr("id");

  //newCartItem.find(".image").css("background-image", "url(" + data.image + ")");  
  //setData(".price", "$" + data.price, newCartItem);

  newCartItem.insertAfter("#cartitem-template");
}

$(".menu-item").click(function() {
  buildCartItem($(this))
})
#cartitem-template {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="cart-item" id="cartitem-template">
  <div class="left">
    <div class="image">image</div>
    <div class="price">price</div>
  </div>
  <div class="mid">
    <div class="name">name
    </div>
    <div class="stars">
      <span>0</span>
    </div>
    <div class="underline"></div>
    <div class="toggleReviews">
      <span></span>
    </div>
  </div>
  <div class="right">
    <div class="remove-cart-item">✕&lt;/div>
  </div>
</div>

<button class="menu-item">Clone</button>

于 2019-09-27T05:13:53.420 回答