【问题标题】:Writing jQuery selector case-insensitive version编写 jQuery 选择器不区分大小写的版本
【发布时间】:2010-10-19 11:33:38
【问题描述】:

我正在使用以下行,我想让它不区分大小写:

var matches = $(this).find('div > span > div#id_to_find[attributeName ^= "filter"]');
if (matches.length > 0) {
}

我的问题是如何使选择器^= 不区分大小写?也许更改为过滤器,然后是一些正则表达式?

【问题讨论】:

标签: jquery jquery-selectors


【解决方案1】:

要进行不区分大小写的属性选择,需要编写自定义选择器函数。

$.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 属性以Rr 开头的input 元素(因此它将匹配RADIOradioRESETreset)。这是一个非常愚蠢的示例,但它应该可以满足您的需求。


关于函数难以理解的注释,我稍微解释一下。

$.expr[':'].iAttrStart = function(obj, params, meta, stack) {

这是创建自定义选择器的标准签名。

var opts = meta[3].match(/(.*)\s*,\s*(.*)/);

meta 是有关呼叫的详细信息数组。 meta[3] 是作为参数传递的字符串。在我的示例中,这是type, r。正则表达式分别匹配 typer

return (opts[1] in obj) && (obj[opts[1]].toLowerCase().indexOf(opts[2].toLowerCase()) === 0);

如果这两个都为真,则返回:

  1. 请求的属性存在于该对象上 (opts[1] in obj)
  2. 搜索词(更改为小写)位于元素属性值的最开头,也更改为小写。

我本可以使用 jQuery 语法而不是原生 JS 语法使这更容易阅读,但这会降低性能。

【讨论】:

  • 感谢您的解决方案!花了一点时间来弄清楚函数的作用,但现在我明白了它有点好。
【解决方案2】:

在这里你可以看到:

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 的回答
【解决方案3】:

在使用 lonesomeday 的答案时有一个小问题。

要重现错误,请尝试以下操作: 页面上的 HTML 标记是常见的 Facebook 元标记:

<meta content="Title of og tag" property="og:title" />

选择器:

$('meta:attrCaseInsensitive(property, og:site_name)')

这行不通。 The reason is because when the selector code gets to the statement (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)
};

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 2012-09-06
    • 2013-04-26
    • 2014-05-22
    • 2014-05-24
    • 2010-09-16
    相关资源
    最近更新 更多