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

标签 javascript jquery html css

我是 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/

相关文章:

php - 将JSON数据发送到PHP并用它来操作MySQL

javascript - React Native 中的 onStartShouldSetPanResponder 与 onMoveShouldSetPanResponder

javascript - 无法使用 AJAX localhost 请求 html 内容

javascript - 如何在重定向后显示另一个页面的隐藏div

html - 在移动设备上保持页面宽度相同

javascript - 计算 li 元素的数量并添加类

html - WKWebView:加载本地html时如何将文本插入HTML

javascript - 在 FOR 循环中等待上一个 AJAX 调用

javascript - 使用 'required' 作为 'select' 标签

javascript - 最小和最大 jQuery 字符计数器