如果所有子项都被“隐藏”,则使用jQuery显示<p>标记,提示“未找到结果”

时间:2019-07-16 10:09:59

标签: jquery

我正在创建一个词汇表页面,并基于可搜索的术语进行页面过滤。我正在用一个简单的脚本在jQuery中完成所有操作。

$("#txtSearch").on('keyup', function() {
    var search = $(this).val().toLowerCase();
    //Go through each list item and hide if not match search

    $(".list-group-item").each(function() {
        if ($(this).html().toLowerCase().indexOf(search) != -1) {
            $(this).show();
        } else {
            $(this).hide();
        }

    });
});
$(document).keyup(function(event) {
    if ($("input#txtSearch").is(":focus") && event.key == "Enter") {
        $('html, body').animate({
            scrollTop: $("#gloss-list-ul").offset().top + (-40)
        }, 600);
    }
});

现在效果很好。但是,如果有人输入不返回任何结果的单词。它没有显示预期,但是当发生这种情况时,如何显示一些文字“索引中的内容与您的条件不符”?

1 个答案:

答案 0 :(得分:1)

添加一个div以显示错误消息。

在jQuery中创建一个变量调用search_result。默认情况下将其设置为false。如果得到结果,则将其设为真。

search_result为false-显示错误消息

search_result为true-错误消息将为空

 $("#txtSearch").on('keyup', function() {
        var search_result = false; //Create a variable call var search_result
        var search = $(this).val().toLowerCase();
        //Go through each list item and hide if not match search

        $(".list-group-item").each(function() {
        if ($(this).html().toLowerCase().indexOf(search) != -1) {
        $(this).show();
        search_result = true; //If getting the result make it true.
        }
        else {
        $(this).hide();  

        }

        if(search_result) {  //search_result is true  - Error message will empty
            $('.display_error_message').html('');
        }else{  //search_result is false - display the error message
            $('.display_error_message').html('Nothing in our index matches your term');
        }

        });
        });

DEMO