编写jQuery选择器不区分大小写的版本
我正在使用以下行,我想使它不区分大小写:
var matches = $(this).find('div > span > div#id_to_find[attributeName ^= "filter"]'); if (matches.length > 0) { }
我的问题是如何使选择器^=
不区分大小写? 也许改成过滤然后一些正则表达式?
要执行不区分大小写的属性选择,您需要编写自定义选择器函数。
$.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
)。 这是一个非常愚蠢的例子,但它应该做你需要的。
重新评论function很难理解,我会解释一下。
$.expr[':'].iAttrStart = function(obj, params, meta, stack) {
这是创建自定义选择器的标准签名。
var opts = meta[3].match(/(.*)\s*,\s*(.*)/);
meta
是有关该调用的一系列详细信息。 meta[3]
是作为参数传递的字符串。 在我的例子中,这是type, r
。 正则表达式分别匹配type
和r
。
return (opts[1] in obj) && (obj[opts[1]].toLowerCase().indexOf(opts[2].toLowerCase()) === 0);
如果两者都是真的,则返回:
- 请求的属性存在于此对象上(
opts[1] in obj
) - 搜索项(更改为小写)位于元素属性值的最开头,也更改为小写。
我本可以使用jQuery语法而不是本机JS语法更容易阅读,但这意味着性能会降低。
在这里你可以看到:
http://www.ericmmartin.com/creating-a-custom-jquery-selector/
你要做的是创建一个自定义jquery选择器:
jQuery.extend(jQuery.expr[':'], { exactIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase() == (m[3]).toLowerCase()" });
然后使用它:
$("#detail select.fields option:exactIgnoreCase(" + q.val() + "):first");
使用lonesomeday的答案时有一个小问题。
要重现错误,请尝试以下操作:页面上的HTML标记是常见的Facebook元标记:
选择:
$('meta:attrCaseInsensitive(property, og:site_name)')
这不行。 原因是当选择器代码到达语句(opts[1] in obj)
,它将执行("property" in obj)
,返回false。 (我不知道为什么)
为了解决这个问题,我刚刚更改了最后一行以使用jQuery的attr()方法
$.expr[':'].iAttrStart = function(obj, params, meta, stack) { var opts = meta[3].match(/(.*)\s*,\s*(.*)/); return (undefined != $(obj).attr(opts[1])) && (obj[opts[1]].toLowerCase().indexOf(opts[2].toLowerCase()) === 0) };