首页 > 解决方案 > 按不包含字母的开头搜索

问题描述

我正在尝试实现搜索功能。但它是通过包含字母来搜索的,我想让它按首字母搜索。谁能帮我?

这是我现有的代码:

jQuery.expr[':'].contains = function(a, index, obj) {
        return jQuery(a).text().toUpperCase()
            .indexOf(obj[3].toUpperCase()) >= 0;
    };

    function funnelInputSearch(thisSearchType) {
        var clientSearch = document.getElementById(thisSearchType),
            thisSearchTypeSelector = $('#' + thisSearchType),
            s = clientSearch.value;
        thisSearchTypeSelector.closest('.tab-pane').find('[class*="itemsList-"] .field-label-wrap').show();
        thisSearchTypeSelector.closest('.tab-pane').find('[class*="itemsList-"] .field-label-wrap:not(:contains("' + s + '"))').hide();
    }
    $('.funnel-input-search input').on('keyup', function () {
        var thisSearchType = $(this).attr('id');
        funnelInputSearch(thisSearchType);
    })

这是小提琴http://jsfiddle.net/5u373deu/6

标签: javascriptjqueryfunctionsearch

解决方案


您可以使用RegExp'test(str)方法。在正则表达式中,插入符号^匹配字符串的开头。

 function searchClients() {
   var clientSearch = document.getElementById("clientSearch");
   var s = clientSearch.value;
   $("span").show();
   $("span").filter(function () {
    return !(new RegExp('^'+(s).toUpperCase()))
       .test((this.textContent || this.innerText || '').toUpperCase());
   }).hide();
 }

searchClients用上面的函数替换你的方法。这样您就不需要在现有的 html 模板上添加任何内容。我们只是简单地选择所有span以默认显示它们,然后隐藏所有与当前搜索输入不匹配的内容。

toUpperCase()请注意不区分大小写的附加内容。如果您希望搜索输入区分大小写,可以删除它们。

我们也使用.filter方法而不是contains选择器。

为了避免修改您现有的 html 模板(例如,必须添加额外的属性,如 anameid到您的 span 以提供搜索查找),我们正在使用textContent和/或innerText读取span的内部 html 内容。

http://jsfiddle.net/appappas1129/xahbL8u6/2/


推荐阅读