我正在构建一个菜单订购应用程序,我必须在其中使用 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">✕</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()
正确吗?老实说卡住了
最佳答案
您甚至在克隆之前就从源元素中删除了属性“id”,这就是为什么在后续方法调用中它找不到 id 为“cartitem-template”的元素。因此,在您的方法 buildCartItem 中,克隆后删除“id”。
const newCartItem = template.clone(false).removeAttr("id");
关于javascript - Jquery .clone() 只能工作一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127955/