javascript - 按不包含字母的开头搜索
问题描述
我正在尝试实现搜索功能。但它是通过包含字母来搜索的,我想让它按首字母搜索。谁能帮我?
这是我现有的代码:
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);
})
解决方案
您可以使用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 模板(例如,必须添加额外的属性,如 aname
或id
到您的 span 以提供搜索查找),我们正在使用textContent
和/或innerText
读取span的内部 html 内容。
推荐阅读
- go - 使用 golang 如何生成 rsa 证书,然后将私钥导出到 pfx 文件,将公钥导出到 cer 文件
- python - 根据数据框中两列之间的差异对字典的值求和并将第一列除以二 - Python
- python - Using lambda functions with apply for Pandas DataFrame
- tfs - how to setup build definition/tfs tasks to handle disconnected build agent properly
- c++ - 获取无限循环而不是值
- sql - checking format without using function in postgresql
- django - FlowRuntimeError 视图流 django
- python - 在 Python 中,我想打印同心正方形,因为我已经编写了代码,但我没有得到想要的输出
- javascript - Mutation Response from Schema When Object is Returned
- python - How to display the best fit equation (in text form) on plot when using numpy.polyfit?