使用Jquery

时间:2016-12-01 05:57:48

标签: javascript jquery

我需要有关如何在li标记内搜索的帮助。 li列表包含以下格式[姓氏,名字]的员工姓名:

Venkata,Anusha  
Raju,Suma

HTML CODE:

<input type="text"  id="comboBox" placeholder="Search.." />
  <ul id="userList"  class="nobull" style="width: 300px; height: 80px;list-style: none; overflow:auto;padding-left:0;">

我使用Jquery搜索结果

$(document).ready(function () {
$('#comboBox').bind('keydown keypress keyup change', function() {
    var search = this.value;
    var $li = $("#userList li").hide();
    $li.filter(function() {
    return $(this).text().indexOf(search) >= 0;
    }).show();
});
});

它工作正常但只有我用第一封信作为资本搜索。 有没有办法让搜索不区分大小写,还可以根据名字或姓氏进行搜索?

2 个答案:

答案 0 :(得分:1)

一种可能的方法是使用regx,

$(document).ready(function () {
    $('#comboBox').bind('keydown keypress keyup change', function() {
        // this will hide all your li!!!
        $("#userList li").hide();

        // define case-insensitive regx
        var reg = new RegExp(this.value, "i");
        //for each li would you require to match?
        $("#userList li").filter(function() {
           return reg.test($(this).text()); 
        }).show();

     });
});

答案 1 :(得分:0)

可以进行不区分大小写的搜索,jQuery允许您添加自己的选择器表达式,我们可以使用它来构建我们自己的包含过滤器,它更加明智:示例就像

jQuery.expr[':'].Contains = function(a,i,m){
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
};

这会为选择器添加一个:Contains()(注意大写)选项,它与:contains()相同,但它首先将所有文本转换为大写,然后比较它们。所以一旦我们将这个添加到你的JavaScript中,我们在listFilter函数中所要做的就是使用Contains()替换:contains(),我们有一个快速,简单,逐步增强的方法来过滤大型列表!

您可以为搜索功能提供此链接, https://kilianvalkhof.com/2010/javascript/how-to-build-a-fast-simple-list-filter-with-jquery/ 希望这会对你有所帮助。

相关问题