【问题标题】:change a div content again and again without losing previous html一次又一次地改变一个 div 内容而不丢失以前的 html
【发布时间】: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


【解决方案1】:

您不是在重新排序产品元素,而是在重写它们。即使产品的 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>

【讨论】:

    猜你喜欢
    • 2012-09-02
    • 2013-09-28
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多