2013-01-17 33 views
1

假設我的部分包含「紅色」,「綠色」和「藍色」頁面。每個頁面都有H1標籤中的標題以及顯示所有三個鏈接的共享#側欄導航。我如何讓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/

+5

如果你添加一些HTML,它會讓生活變得更容易! – ManseUK

+2

一些代碼/標記會很好 –

+0

創建一個[jsFiddle](http://jsfiddle.net/)並在您的問題中顯示鏈接。 –

回答

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>); 
    } 
}); 

相關的文檔 - >.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

+0

完美,非常感謝。我爲我的問題添加了小提琴,試圖弄清楚爲什麼你的作品和我的不是!感謝您發佈解決方案。 – Chris

+2

@Chris - 你沒有工作,因爲你選擇了jsfiddle中的mootools,而不是jquery! – Jamiec

+1

@Chris嘗試 - > http://jsfiddle.net/manseuk/BxCgT/1/ < - 與Jamiec的建議 – ManseUK

相關問題