在选择时如何使用jQuery忽略大小写?
-
03-07-2019 - |
题
我目前正在尝试使用以下jQuery选择器禁用链接:
$("a[href$=/sites/abcd/sectors]").removeAttr("href");
问题在于,有时href在页面上可能并不总是小写。发生这种情况时,选择器不再匹配。
有谁知道怎么解决这个问题?我可以更改此行为一次以忽略大小写吗?
解决方案
我自己遇到了这个问题。我稍微改变了一下逻辑,让我无需比较它。它需要更多的工作,但至少它是有效的。
$('a').each(function(i,n) {
var href = $(n).attr("href");
href = href.toLowerCase();
if (href.endsWith('/sites/abcd/sectors'))
$(n).removeAttr('href');
});
您必须弄清楚自己的endsWith
逻辑。
其他提示
jQuery是为了扩展而构建的。您可以更正它或添加您自己的不区分大小写的选择器类型。
你可以使用函数<!>“;是<!>;在jQuery中。它不区分大小写。
$("a").each(function() {
if ($(this).is("a[href$=/sites/abcd/sectors]")) {
$(this).removeAttr('href');
}
})
首先这是 NOT VALID 表达式,因为它包含\
,
如果您希望将任何元字符(例如!"#$%&'()*+,./:;<=>?@[\]^``{|}~
)用作
名称的文字部分,您必须使用两个反斜杠转义字符:\\
。
Src: http://api.jquery.com/category/selectors/
所以你必须将/
转义为\\/
所以你的表达式将是$("a[href$=\\/sites\\/abcd\\/sectors]").removeAttr("href");
不隶属于 StackOverflow