【发布时间】:2021-11-04 19:51:32
【问题描述】:
我正在编写一个 jquery 函数来按类型过滤产品。它工作得很好,但是当我不止一次按类型过滤时。名为 addToWishlist 的产品框的 Html 元素停止工作。 否则所有产品都显示得很好。 无法弄清楚问题出在哪里。 这是代码
//load products data in array
var productArray = [];
$("#product-items .col-4").each (function (){
productArray.push($(this)) })
$(".filter-btn").click(function(e) {
var btnId = e.target.id;
var tempArray = [];
for(var i = 0;i < productArray.length; i++){
var type = $(productArray[i]).find('.addToWishlist').data("type");
if(btnId == "fairness-soaps" && type == "Fairness")
tempArray.push(productArray[i])
if(btnId == "deep-clean-soaps" && type == "Deep-Clean")
tempArray.push(productArray[i])
if(btnId == "skin-whitening-soaps" && type == "Skin-Whitening")
tempArray.push(productArray[i])
}
$("#product-items").html(tempArray);
});
<div class="row" id="product-items">
<div class="col-4">
<a href="#">
<div class="product-box">
<div class="product-img">
<img src="images/product-img13.png" alt="">
<a type="button" class="addToWishlist" data-id="13" data-image="images/product-img13.png" data-price="$30"
data-name="Aloe Vera Soap" data-quantity="1" data-weight="50g" data-availability="In Stock" data-type="Fairness">
<i class="wishlist-icon fa fa-heart-o"></i></a>
</div>
<p class="product-name">Aloe Vera Soap</p>
<p class="product-price">$30</p>
</div>
</a>
</div>
and so on....
【问题讨论】:
-
我猜您遇到了及时加载问题,以及您使用 jquery 的方式。
-
我可以看到,您正在这里动态绑定新元素 $("#product-items").html(tempArray);。尝试将其绑定到 product-items 部分。如果您打算将其用作按钮,请在 $("#product-items").html(tempArray); 之后调用该事件。
标签: javascript html jquery arrays filter