contains 和 toLowerCase() 的 jQuery 用法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8795752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery usage of contains and toLowerCase()
提问by Or Weinberger
I'm trying to compare a string given in an input to a div's content using jQuery contain
.
我正在尝试使用 jQuery 将输入中给出的字符串与 div 的内容进行比较contain
。
Problem is, I want to be able to check if the string is contained regardless of upper/lower case.
问题是,无论大小写,我都希望能够检查字符串是否包含在内。
This is my function:
这是我的功能:
$(document).ready(function() {
drawDimensions('dContent');
$('#dSuggest').keyup(function() {
var dInput = this.value;
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
});
So if one of the .dDimension divs contains 'Date' and a user presses the 'd' key, I want to show that item.
因此,如果 .dDimension div 之一包含“日期”并且用户按下“d”键,我想显示该项目。
is it possible?
是否可以?
回答by Felix Kling
You can use .filter
[docs]:
您可以使用.filter
[文档]:
var dInput = this.value.toLowerCase();
$(".dDimension").filter(function() {
return $(this).text().toLowerCase().indexOf(dInput) > -1;
}).css("display","block");
回答by Christofer Eliasson
Have a look at this example, he extend the jQuery selectors with a case-insensitive contains selector that he calls containsi, like this:
看一下这个例子,他用一个不区分大小写的 contains 选择器扩展了 jQuery 选择器,他称之为 containsi,像这样:
$.extend($.expr[':'], {
'containsi': function (elem, i, match, array) {
return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || '').toLowerCase()) >= 0;
}
});
回答by ShankarSangoli
You can write your own selector by extending jQuery. Try this
您可以通过扩展 jQuery 来编写自己的选择器。尝试这个
$.extend($.expr[':'], {
'containsi': function(elem, i, match, array)
{
return (elem.textContent || elem.innerText || '').toLowerCase()
.indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
Useage $(".dDimension:containsi('" + dInput + "')").css("display","block");
用途 $(".dDimension:containsi('" + dInput + "')").css("display","block");
回答by mqsoh
The last comments in the jQuery documentation for containsprovides an 'icontains' implementation that may suit you.
jQuery 文档中关于 contains的最后一条评论提供了一个可能适合您的“icontains”实现。
$.expr[':'].icontains = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};
// Example usage.
$("div:icontains('John')").css("text-decoration", "underline");