如何为照片库搜索框jquery添加不区分大小写

时间:2016-03-18 22:50:08

标签: javascript jquery

伙计我是“新手”。我的任务很小。我必须为“照片库”创建一个搜索框。我是通过在HTML列表项中使用“data-keywords”来实现的,我也是为了响应大小写,但问题是我想要不区分大小写,但无法弄清楚如何做到这一点。有一些建议使用“:contains”选择器与RegEx一起使用,但要么我不能实现这些建议,要么我完全搞砸了代码。这是代码https://jsfiddle.net/Lnvaagd3/先谢谢你!)!

$("#search").keyup(function() {

    var currentQuery = $("#search").val();

    if (currentQuery !== "") {

        $("#list li").fadeOut(100);

        $("#list li").each(function() {

            var currentKeyword = $(this).attr("data-keywords");

            if (currentKeyword.toLowerCase().indexOf(currentQuery) >= 0) {

                $(this).fadeIn(200);

            } else if (currentKeyword.toUpperCase().indexOf(currentQuery) >= 0) {

                $(this).fadeIn(200);
            }

        });

    } else {

        $("#list li").fadeIn(200);

    }

});

1 个答案:

答案 0 :(得分:1)

尝试使用:

var currentQuery = $("#search").val().toLowerCase();
// ----------------------------------^^^^^^^^^^^^^^

使用它你不需要else if

这样,currentQuerycurrentKeyword都将使用lowerCase字母,换句话说,这一行:

if (currentKeyword.toLowerCase().indexOf(currentQuery) >= 0) {

将作为不区分大小写。

希望它有所帮助。