0

http://jsbin.com/aguver/17/edit 经过多次搜索,我在这里找到了这段代码。它正在设置活动类别并将其从原来的位置删除。问题是,当它应该只是一个时,它正在将 2 个链接更改为红色。

使用正则表达式/^\w/可能会起作用,但不像代码中设计的那样,因为它是放置在 css 选择器中的变量。它的搜索/选择对我的目的来说太模糊了。

谢谢。

HTML:

<!DOCTYPE html>
<html>
<head>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><meta charset=utf-8 />
<title>demo by roXon</title>
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
  *{margin:0;padding:0;}
  ul{list-style:none;}
  a{text-decoration:none;}
  a.active{color:red;}
</style>
</head>
<body>
  <div>
     <ul id="books">
         <li><a href="nonfiction">Nonfiction</a></li>
         <li><a href="fiction">Fiction</a></li>
     </ul>  
  </div>
</body>
</html>

JS:

var url = 'http://www.domain.com/fiction'; //<-- too similar to nonfiction

//actually it just checks the last character, I need regex maybe

var link = url.split('/').slice(-1);

document.write(url.split('/').slice(-1));

$('#books li a[href$="'+link+'"]').addClass('active');
//Script is supposed to select the active link via the url and giving it a class attribute
4

0 回答 0