编写jQuery选择器不区分大小写的版本 [英] Writing jQuery selector case-insensitive version
问题描述
我正在使用以下行,并且希望使其不区分大小写:
I'm using following line and I would like to make it case-insensitive:
var matches = $(this).find('div > span > div#id_to_find[attributeName ^= "filter"]');
if (matches.length > 0) {
}
我的问题是,如何使选择器^=
不区分大小写?也许更改为过滤器,然后再添加一些正则表达式?
My question is that how can I make the selector ^=
to be case-insensitive? Maybe changing to filter and then some regexp?
推荐答案
要选择不区分大小写的属性,您需要编写一个自定义选择器函数.
To do a case-insensitive attribute selection, you need to write a custom selector function.
$.expr[':'].iAttrStart = function(obj, params, meta, stack) {
var opts = meta[3].match(/(.*)\s*,\s*(.*)/);
return (opts[1] in obj) && (obj[opts[1]].toLowerCase().indexOf(opts[2].toLowerCase()) === 0);
};
您可以这样使用:
$('input:iAttrStart(type, r)')
这将匹配其type
属性以R
或r
开头的所有input
元素(因此它将匹配RADIO
,radio
,RESET
或reset
).这是一个非常愚蠢的示例,但是它应该可以满足您的需求.
This will match any input
elements whose type
attribute begins with R
or r
(so it would match RADIO
, radio
, RESET
or reset
). This is a pretty silly example, but it should do what you need.
关于该功能难以理解的评论,我将对其稍作解释.
Re the comment that the function is hard to understand, I'll explain it a little.
$.expr[':'].iAttrStart = function(obj, params, meta, stack) {
这是用于创建自定义选择器的标准签名.
This is the standard signature for creating custom selectors.
var opts = meta[3].match(/(.*)\s*,\s*(.*)/);
meta
是有关调用的详细信息的数组. meta[3]
是作为参数传递的字符串.在我的示例中,这是type, r
.正则表达式分别匹配type
和r
.
meta
is an array of details about the call. meta[3]
is the string passed as the parameter. In my example, this is type, r
. The regex matches type
and r
separately.
return (opts[1] in obj) && (obj[opts[1]].toLowerCase().indexOf(opts[2].toLowerCase()) === 0);
如果这两个条件都成立,则返回:
Return if both these are true:
- 请求的属性存在于此对象(
opts[1] in obj
) - 搜索项(更改为小写)位于元素属性值的开头,也更改为小写.
我本可以使用jQuery语法而不是本机JS语法来使其更易于阅读,但这将意味着性能降低.
I could have made this easier to read using jQuery syntax rather than native JS syntax, but that would have meant reduced performance.
这篇关于编写jQuery选择器不区分大小写的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!