CSS 选择器对属性不区分大小写 [英] CSS selector case insensitive for attributes

查看:32
本文介绍了CSS 选择器对属性不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 HTML 元素 <input type="submit" value="Search"/> 一个 css 选择器需要区分大小写:

If I have an HTML element <input type="submit" value="Search" /> a css selector needs to be case-sensitive:

input[value='Search'] 匹配

input[value='search'] 不匹配

我需要一个不区分大小写的方法也可以工作的解决方案.我正在使用 Selenium 2Jquery,所以两者的答案都是欢迎.

I need a solution where the case-insensitive approach works too. I am using Selenium 2 and Jquery, so answers for both are welcome.

推荐答案

它现在存在于 CSS4 中,参见 this answer.

It now exists in CSS4, see this answer.

否则,对于 jQuery,你可以使用...

Otherwise, for jQuery, you can use...

$(':input[name]').filter(function() {
   return this.value.toLowerCase() == 'search';
});

jsFiddle.

您还可以制作自定义选择器...

You could also make a custom selector...

$.expr[':'].valueCaseInsensitive = function(node, stackIndex, properties){
     return node.value.toLowerCase() == properties[3];
};

var searchInputs = $(':input:valueCaseInsensitive("Search")');

jsFiddle.

如果只做一次自定义选择器有点矫枉过正,但如果您需要在应用程序中多次使用它,这可能是个好主意.

The custom selector is a bit of overkill if doing this once, but if you need to use it many times in your application, it may be a good idea.

是否可以为任何属性使用这种自定义选择器?

Is it possible to have that kind of custom selector for any attribute?

当然,请查看以下示例.这有点令人费解(诸如 :input[value:toLowerCase="search"] 之类的语法可能更直观),但它确实有效 :)

Sure, check out the following example. It's a little convoluted (syntax such as :input[value:toLowerCase="search"] may have been more intuitive), but it works :)

$.expr[':'].attrCaseInsensitive = function(node, stackIndex, properties){
    var args = properties[3].split(',').map(function(arg) {
        return arg.replace(/^s*["']|["']s*$/g, '');  
    });
    return $(node).attr(args[0]).toLowerCase() == args[1];
};

var searchInputs = $('input:attrCaseInsensitive(value, "search")');

jsFiddle.

您可能可以使用 eval() 使该字符串成为一个数组,但我发现这样做更舒服(并且您不会意外执行放置在选择器中的任何代码).

You could probably use eval() to make that string an array, but I find doing it this way more comfortable (and you won't accidentally execute any code you place in your selector).

相反,我在 分隔符上拆分字符串,然后在每个数组成员的任一侧剥离空格、'".请注意,引号内的 , 不会按字面意思对待.没有理由从字面上要求一个,但您总是可以针对这种可能性进行编码.我会把它留给你.:)

Instead, I am splitting the string on , delimiter, and then stripping whitespace, ' and " either side of each array member. Note that a , inside a quote won't be treated literally. There is no reason one should be required literally, but you could always code against this possibility. I'll leave that up to you. :)

我不认为 map() 具有最好的浏览器支持,因此您可以显式迭代 args 数组或 扩充Array对象.

I don't think map() has the best browser support, so you can explictly iterate over the args array or augment the Array object.

这篇关于CSS 选择器对属性不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆