显示'没有项目'使用jQuery插件过滤列表项时的消息

Display 'no items' message when using jQuery plugin to filter list items

本文关键字:列表 消息 过滤 使用 项目 显示 jQuery 插件      更新时间:2023-09-26

我正在使用CSS技巧网站上的"过滤块"教程,该教程允许您按类别过滤项目列表。

它在我正在开发的活动网站上运行得很好,但如果某个类别中没有项目,则无法显示消息,例如"该类别中没有即将举办的活动"。

代码的工作原理是将类别导航中的ID与主列表中的类相匹配。"style="display:none;"'添加到与用户所选类别不匹配的任何列表项中。

以下是类别导航标记:

<ul id="category-filter">
    <li><a href="#" id="all" class="current">VIEW ALL</a></li>
    <li><a href="#" id="arts" class="filter">Arts</a></li>
    <li><a href="#" id="conference" class="filter">Conferences</a></li>
    <li><a href="#" id="exhib" class="filter">Exhibitions</a></li>
    <li><a href="#" id="faith" class="filter">Faith</a></li>
    <li><a href="#" id="lecture" class="filter">Lectures</a></li>
    <li><a href="#" id="open" class="filter">Open days</a></li>
    <li><a href="#" id="sport" class="filter">Sport</a></li>
</ul>

以下是一些事件的示例:

<ul id="events-list">
    <li class="event open">
        <h3><a href="#">Open day title</a></h3>
        <small>Date and time</small>
    </li>
    <li class="event conference">
        <h3><a href="#">Conference title</a></h3>
        <small>Date and time</small>           
    </li>
    <li class="event sport">
        <h3><a href="#">Sport title</a></h3>
        <small>Date and time</small>           
    </li>
</ul>

最后,jQuery代码:

$(function(){
    $("#all").click(function(){
        $(".event").slideDown("fast");
        $("#category-filter a").removeClass("current");
        $(this).addClass("current");
        return false;
    });
    $(".filter").click(function(){
        var thisFilter = $(this).attr("id");
        $(".event").slideUp("fast");
        $("."+ thisFilter).slideDown("fast");
        $("#category-filter a").removeClass("current");
        $(this).addClass("current");
        return false;
    });
});

是否可以在适当的时候更改或添加到此代码以显示"无事件"消息?如果是这样的话,任何帮助都将不胜感激,因为我根本不知道从哪里开始!

非常感谢。

这应该有效:

添加一个<li>,专门用于显示未找到结果消息:

<li class="event noresults">
    <h3>No results</h3>
    <small>please select a different category</small>           
</li>

将脚本更改为:

$(function() {
    // hide the noresults <li>
    $(".noresults").hide();
    $(".filter").click(function() {
        var thisFilter = $(this).attr("id");
        $(".event").slideUp("fast");
        // get a list of filtered items
        var $filteredItems = $("." + thisFilter);
        // if there are none, show something special
        if ($filteredItems.size() == 0) {
            // show the noresults message
            $(".noresults").slideDown("fast");
        }
        else {
            // open the filtereditems 
            $filteredItems.slideDown("fast");
        }
        $("#category-filter a").removeClass("current");
        $(this).addClass("current");
        return false;
    });
});

$("."+ thisFilter).length将告诉您将显示多少项。然后,您可以拥有一个包含此消息的div,并根据该值显示或隐藏它。