我是 javascript/jQuery 的新手,如果页面的 url 不匹配 三个字符串之一,我正在尝试向元素添加一个 css 类。我无法使用这些代码行。
if (window.location.href.match(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}
有什么想法吗?我的语法不正确吗?
编辑:
似乎每个人给我的答案都应该有效,但事实并非如此。也许我的代码的其他行有冲突:
$(document).ready(function() {
if (window.location.href.search(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}
if (window.location.href.match(/(interests)/) != null) {
jQuery("#nav-interests").addClass('active');
}
if (window.location.href.match(/(ideas)/) != null) {
jQuery("#nav-ideas").addClass('active');
}
if (window.location.href.match(/(art)/) != null) {
jQuery("#nav-art").addClass('active');
}
});
我的网站是benxd.me .此主页上的链接 #nav-about
需要 active
类;该脚本在此页面上不起作用。其他页面上的脚本、兴趣、想法和摄影作品。
最佳答案
对于您正在做的事情,您想使用 .search()
不是.match()
. .search()
的返回值是第一个匹配项的索引,如果没有匹配项,则为 -1
。 .match()
的返回值是:
An Array containing the entire match result and any parentheses-captured matched results;
null
if there were no matches.
解决上述问题,并且假设您已经声明要在 URL 不匹配时添加类,代码应该是:
if (window.location.href.search(/(interests|ideas|art)/) === -1) {
jQuery("#nav-about").addClass('active');
}
关于javascript - 如果 window.location.href 不匹配某个字符串,则将 css 类添加到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187927/