如果window.location.href不匹配某个字符串,则为元素添加css类

If window.location.href does not match a certain string, add css class to element

本文关键字:元素 添加 css 字符串 location window href 不匹配 如果      更新时间:2023-09-26

我是新的javascript/jQuery和我试图添加一个css类的元素,如果页面的url 不匹配三个字符串之一。我的这几行代码不能工作了。

  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()的返回值为:

包含整个匹配结果和任何括号捕获的匹配结果的数组;null,如果没有匹配。

修复上述问题,并且考虑到您已经声明要在URL 匹配时添加类,代码应该是:

if (window.location.href.search(/(interests|ideas|art)/) === -1) {
    jQuery("#nav-about").addClass('active');
}

可以使用string。搜索或字符串。js中的indexOf方法。下面是一个示例代码:

var url = 'http://localhost:3000/interests';
var url1 = 'http://localhost:3000/ideas';
if (url.search('interests') > -1) {
  // do your work
}

if (url1.indexOf('ideas') > -1) {
  // do your work
}

给你小提琴。

https://jsfiddle.net/Refatrafi/grxpmaon/3/

我使用下面的函数来执行相同的基本过程。

function NavSetActiveLink() {
    var currentLocation = window.location.pathname;
    $(".nav-element a").each(function(){
        if ($(this).attr('href') === currentLocation){
            $(this).addClass('active');
            return false; // break out of the loop
        }
    });
}

函数循环遍历每个.nav-element a,并找到第一个具有与当前window.location.pathname匹配的href的<a>,假设存在相对链接。

只要你的nav元素有一个直接相关的<a>标签,即父元素或子元素或self,你就可以做到这一点。