将类添加到第二个文本实例

时间:2013-01-17 11:56:08

标签: jquery

让我们说我的部分包含页面" Red"," Green"和"蓝"。每个页面都有H1标签中的标题以及显示所有三个链接的共享#sidebar导航。如何让jQuery检测H1中输入的文本,在#sidebar中找到相同的文本,如果找到匹配项,则在#sidebar链接中添加一个类?

HTML:

<h1>Red</h1>
<div id="sidebar">
  <a href="#">Red</a><br>
  <a href="#">Green</a><br>
  <a href="#">Blue</a>
</div>

CSS:

#sidebar { float: right; }
.current-section { background: red; }

抱歉 - 我是jQuery的初学者。这是一个小提琴:http://jsfiddle.net/BxCgT/

1 个答案:

答案 0 :(得分:2)

这样的事可能有用......

// get title text
var title = $('h1').text();
// loop anchors in #sidebar
$('#sidebar a').each(function() {
   // if anchor text matches title
   if($(this).text() == title) {
     // add a class
     $(this).addClass(<yourclass>);
   }
});

相关文档 - &gt; .text() .each().addClass()

我假设您的代码看起来像这样:

<h1>Red</h1>
<div id="sidebar">
   <a href="red.html">Red</a><br>
   <a href="green.html">Green</a><br>
   <a href="blue.html">Blue</a>
</div>

Working example

相关问题