jQuery 删除然后再次添加以进行实时搜索

jQuery remove then add again for live search

本文关键字:实时 搜索 添加 删除 然后 jQuery      更新时间:2023-09-26

所以我有一组动态创建的内容"盒子",由wordpress插件生成。每个框都包含在一个带有"头页帖子"类的div 中。我正在尝试创建一个"实时搜索",它将删除不匹配的框,但当用户更改或删除其搜索词时,也会将它们添加回来。

使用 $(this).

fadeOut(); 和 $(this).fadeIn(); 有效,但由于框实际上并未被删除 - 只是隐藏 - 页面布局不会动态更新,并且框保留在原来的位置。如果我使用 $(this).remove() 完全删除框,我可以更新页面布局;但是如果搜索词更新,无法弄清楚如何重新添加它们。 尝试将它们存储在带有类"store"的页面上的隐藏div 中,但这也不起作用。

我正在处理的页面在这里。 这是我的代码;任何帮助将不胜感激!谢谢!

<script type="text/javascript">
$(document).ready(function(){
    $("#filter").keyup(function(){
    // Retrieve the input field text and reset the count to zero
    var filter = $(this).val(), count = 0;
    // Loop through the comment list
    $(".front-page-post").each(function(){
        // If the list item does not contain the text phrase fade it out
        if ($(this).text().search(new RegExp(filter, "i")) < 0) { 
            $(this).clone().appendTo("div.store");
            $(this).remove().delay(500); $(window).resize();
        // Show the list item if the phrase matches and increase the count by 1
        } else {
          $(this).prepend( function() { $("div.store").contents(); } );
            count++;
        }
    });
    // Update the count
    var numberItems = count;
    $("#filter-count").text("Number of Resources = "+count);
    });
});
</script>

我花了一段时间才弄清楚,但这似乎在我的浏览器上运行良好。

第一行只是禁用您的功能,所以我可以在控制台中尝试它,您不需要它。

工作糊剂样品

看起来该网站已经使用 positin:absolute 和顶部、左侧定位了块,这意味着即使您删除了这些框,您也必须重新计算这些块。