18910140161

JavaScript-反复更改DIV内容而不丢失以前的HTML-堆栈溢出

顺晟科技

2022-10-18 12:44:27

37

我正在编写一个jQuery函数来按类型过滤产品。它工作得非常好,但当我按类型过滤一次以上。名为AddToWishList的Product-Box的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....

顺晟科技:

你不是在重新排序产品元素,而是在重写它们。即使产品的HTML是相同的,当您调用$("#product-items").html(tempArray);。您需要将事件重新应用于";AddToWishList";按钮或重新排序元素,而不是直接写入HTML.

这里有一个人为的例子,它显示了仅仅因为HTML是相同的并不意味着事件保持不变:

<div id="container">
    <button id="special-button">Click me</button>
</div>
<script>
    $("#special-button").on("click", function(){
        alert("I've Been clicked!");
    });
    $("#container").html(`<button id="special-button">Click me</button>`);
</script>
  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航