javascript 使用 Jquery 不区分大小写的属性值选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5755722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Case-insensitive attribute-value selector with Jquery
提问by Josh Johnson
I need to get the value of the content
attribute of a certain meta
tag.
我需要获取content
某个meta
标签的属性值。
var someContent = $("meta[name=someKindOfId]").attr("content");
is how I usually do it. For business reasons, someKindOfId
may be somekindofid
. It could be other combinations of cases as well. I don't know.
这是我通常的做法。出于商业原因,someKindOfId
可能会somekindofid
。也可以是其他情况的组合。我不知道。
What is the best way to search for this meta tag? Adding an id or other identifier is out of the question.
搜索此元标记的最佳方法是什么?添加 id 或其他标识符是不可能的。
回答by Nicky Waites
You could use the jquery filter function like so
您可以像这样使用 jquery 过滤器功能
var meta = $('meta[name]').filter(function() {
return this.name.toLowerCase() == 'somekindofid';
});
Based upon CSS selector case insensitive for attributes
回答by Flash
Also, for case insensitive attribute *= selector:
此外,对于不区分大小写的属性 *= 选择器:
$("meta[name*=someKindOfId]")
You can use:
您可以使用:
$('meta').filter(function() {
return (/somekindofid/i).test($(this).attr('name'));
}).attr("content")
回答by alexcasalboni
How about this?
这个怎么样?
You can reuse the case-insensitive jQuery expression, as shown in the snippet below (execute it to see how the first div matches, while the second does not).
您可以重用不区分大小写的jQuery 表达式,如下面的代码片段所示(执行它以查看第一个 div 如何匹配,而第二个不匹配)。
$.expr[':'].iAttrContains = function(node, stackIndex, properties){
var args = properties[3].split(',').map(function(arg) {
return arg.replace(/^\s*["']|["']\s*$/g, '');
});
if ($(node).attr(args[0])) {
//exact match:
return $(node).attr(args[0]).toLowerCase() == args[1].toLowerCase();
//if you actually prefer a "contains" behavior:
//return -1 !== $(node).attr(args[0]).toLowerCase().indexOf(args[1].toLowerCase());
}
};
$("div:iAttrContains('data-name', 'test')").addClass('matched');
div{background:red;}
div.matched{background:green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div data-name="This is a test">First div</div>
<div data-name="This is a div">Second div</div>