[英]Is there a case insensitive jQuery :contains selector?
What I ended up doing for jQuery 1.2 is :我最终为 jQuery 1.2 做的是:
jQuery.extend(
jQuery.expr[':'], {
Contains : "jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
});
This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.这将扩展 jquery 以具有不区分大小写的 :Contains 选择器, :contains 选择器保持不变。
Edit: For jQuery 1.3 (thanks @user95227) and later you need编辑:对于 jQuery 1.3(感谢@user95227)及更高版本,您需要
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
Edit: Apparently accessing the DOM directly by using编辑:显然通过使用直接访问 DOM
(a.textContent || a.innerText || "")
instead of代替
jQuery(a).text()
In the previous expression speeds it up considerably so try at your own risk if speed is an issue.在前面的表达式中,它大大加快了速度,所以如果速度是一个问题,请自担风险。 (see @John 's question ) (见@John的问题)
Latest edit: For jQuery 1.8 it should be:最新编辑:对于 jQuery 1.8,它应该是:
jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function(arg) {
return function( elem ) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
To make it optionally case insensitive: http://bugs.jquery.com/ticket/278使其可选不区分大小写: http : //bugs.jquery.com/ticket/278
$.extend($.expr[':'], {
'containsi': function(elem, i, match, array)
{
return (elem.textContent || elem.innerText || '').toLowerCase()
.indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
then use :containsi
instead of :contains
然后使用:containsi
而不是:contains
As of jQuery 1.3, this method is deprecated.从 jQuery 1.3 开始,不推荐使用此方法。 To get this to work it needs to be defined as a function:为了让它工作,它需要定义为一个函数:
jQuery.expr[':'].Contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
If someone (like me) is interested what do a and m[3] mean in Contains definition.如果有人(像我一样)对包含定义中的a和m[3]表示什么感兴趣。
KEY/LEGEND: Params made available by jQuery for use in the selector definitions:关键/图例:jQuery 提供的参数可用于选择器定义:
r = jQuery array of elements being scrutinised. r = 正在检查的元素的 jQuery 数组。 (eg: r.length = Number of elements) (例如: r.length = 元素数)
i = index of element currently under scrutiny, within array r . i = 当前正在审查的元素的索引,在数组r 中。
a = element currently under scrutiny. a = 当前正在审查的元素。 Selector statement must return true to include it in its matched results. Selector 语句必须返回 true 才能将其包含在其匹配结果中。
m[2] = nodeName or * that we a looking for (left of colon). m[2] = nodeName 或 * 我们正在寻找(冒号左侧)。
m[3] = param passed into the :selector(param). m[3] = param 传入 :selector(param)。 Typically an index number, as in :nth-of-type(5) , or a string, as in :color(blue) .通常是索引号,如:nth-of-type(5) ,或字符串,如:color(blue) 。
In jQuery 1.8 you will need to use在 jQuery 1.8 中,您需要使用
jQuery.expr[":"].icontains = jQuery.expr.createPseudo(function (arg) {
return function (elem) {
return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
A variation that seems to perform slightly faster and that also allows regular expressions is:一个似乎执行得稍微快一点并且也允许使用正则表达式的变体是:
jQuery.extend (
jQuery.expr[':'].containsCI = function (a, i, m) {
//-- faster than jQuery(a).text()
var sText = (a.textContent || a.innerText || "");
var zRegExp = new RegExp (m[3], 'i');
return zRegExp.test (sText);
}
);
Not only is this case-insensitive, but it allows powerful searches like:这不仅不区分大小写,而且允许强大的搜索,例如:
$("p:containsCI('\\\\bup\\\\b')")
(Matches "Up" or "up", but not "upper", "wakeup", etc.) $("p:containsCI('\\\\bup\\\\b')")
(匹配“Up”或“up”,但不匹配“upper”、“wakeup”等)$("p:containsCI('(?:Red|Blue) state')")
(Matches "red state" or "blue state", but not "up state", etc.) $("p:containsCI('(?:Red|Blue) state')")
(匹配“红色状态”或“蓝色状态”,但不匹配“向上状态”等)$("p:containsCI('^\\\\s*Stocks?')")
(Matches "stock" or "stocks", but only at the start of the paragraph (ignoring any leading whitespace).) $("p:containsCI('^\\\\s*Stocks?')")
(匹配“stock”或“stocks”,但仅在段落的开头(忽略任何前导空格)。)May be late.... but,可能会迟到......但是,
I'd prefer to go this way..我宁愿走这条路..
$.extend($.expr[":"], {
"MyCaseInsensitiveContains": function(elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
This way, you DO NOT tamper with jQuery's NATIVE '.contains' ... You may need the default one later...if tampered with, you might find yourself back to stackOverFlow ...这样,您就不会篡改 jQuery 的 NATIVE '.contains' ...您以后可能需要默认的...如果被篡改,您可能会发现自己又回到了stackOverFlow ...
jQuery.expr[':'].contains = function(a,i,m){
return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
The update code works great in 1.3, but "contains" should be lower case on the first letter unlike the previous example.更新代码在 1.3 中效果很好,但与前面的示例不同,“包含”的第一个字母应该是小写的。
Refer below to use ":contains" to find text ignoring its case sensitivity from an HTML code,请参阅下文以使用“:contains”从 HTML 代码中查找忽略大小写的文本,
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
$("#searchTextBox").keypress(function() {
if($("#searchTextBox").val().length > 0){
$(".rows").css("display","none");
var userSerarchField = $("#searchTextBox").val();
$(".rows:contains('"+ userSerarchField +"')").css("display","block");
} else {
$(".rows").css("display","block");
}
});
You can also use this link to find case ignoring code based on your jquery version, Make jQuery :contains Case-Insensitive您还可以使用此链接根据您的 jquery 版本查找忽略大小写的代码, Make jQuery :contains Case-Insensitive
A faster version using regular expressions.使用正则表达式的更快版本。
$.expr[':'].icontains = function(el, i, m) { // checks for substring (case insensitive)
var search = m[3];
if (!search) return false;
var pattern = new RegExp(search, 'i');
return pattern.test($(el).text());
};
I had a similar problem with the following not working...我遇到了类似的问题,以下不起作用...
// This doesn't catch flac or Flac
$('div.story span.Quality:not(:contains("FLAC"))').css("background-color", 'yellow');
This works and without the need for an extension这有效并且不需要扩展
$('div.story span.Quality:not([data*="flac"])').css("background-color", 'yellow');
This works too, but probably falls into the "manually looping" category....这也有效,但可能属于“手动循环”类别......
$('div.story span.Quality').contents().filter(function()
{
return !/flac/i.test(this.nodeValue);
}).parent().css("background-color", 'yellow');
New a variable I give it name subString and put string you want to search in some elements text.新建一个变量,我将其命名为 subString 并将要搜索的字符串放入某些元素文本中。 Then using Jquery selector select elements you need like my example $("elementsYouNeed")
and filter by .filter()
.然后使用 Jquery 选择器选择您需要的元素,例如我的示例$("elementsYouNeed")
并按.filter()
过滤。 In the .filter()
it will compare each elements in $("elementsYouNeed")
with the function.在.filter()
它会将$("elementsYouNeed")
每个元素与函数进行比较。
In the function i using .toLowerCase()
for element text also subString that can avoid case sensitive condition and check if there is a subString in it.在我对元素文本使用.toLowerCase()
的函数中,还有 subString 可以避免区分大小写的条件并检查其中是否有 subString。 After that the .filter()
method constructs a new jQuery object from a subset of the matching elements.之后.filter()
方法从匹配元素的子集构造一个新的 jQuery 对象。
Now you can get the match elements in matchObjects and do whatever you want.现在您可以在 matchObjects 中获取 match 元素并做任何您想做的事情。
var subString ="string you want to match".toLowerCase();
var matchObjects = $("elementsYouNeed").filter(function () {return $(this).text().toLowerCase().indexOf(subString) > -1;});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.