2011-11-24 67 views
3

以下代碼顯示了我的div實現的側面菜單。JQuery HTML Div導航

<div class="top_link"> 
    <h3><a href="/dashboard/" class="dash_board_link">Dashboard</a></h3> 
</div> 
<div id="accordion" class="accordion_menu"> 
    <h3><a href="#section1">Hits</a></h3> 
    <div class="content"> 
     <a href="/dailyhits/">Daily Hits</a> 
     <a href="/tophundredurls/?page=1">Top 100 URL</a> 
    </div> 
</div> 
<div class="bottom_link"> 
    <h3><a href="/userwatchlist">Watch Lists</a></h3> 
</div> 
<div class="bottom_link"> 
    <h3><a href="/twitterinsights">Twitter Insights</a></h3> 
</div> 
<div class="bottom_link selected"> 
    <h3><a href="/managedomain"> Manage Domain </a></h3> 
</div> 

使用jQuery我想讀取當前的URL,它修剪到這是在href屬性指定的格式,如果有比賽我想具體div元素的選定部分添加到div class="xxx select"。爲了做到這一點,我添加了下面的jQuery代碼:

$(document).ready(function() { 
    var pathname = window.location.pathname; 
}); 

我不知道如何繼續進行,因爲這樣庵新的jQuery。

回答

2

有沒有嘗試過,但沿着這些lings東西應該工作:

var pathname = window.location.pathname; 
var pathPart = pathname.slice('.com/', '/'); // assuming this is the end of your url 
$('#navigation a').click(function(){ 
    var url = $(this).attr('href'); 
    $('#navigation a').removeClass('active'); 
    if (pathPart == url) { 
     $(this).addClass('active'); 
    } 
}); 
+2

一個注意事項 - 即在ie中(我認爲最高版本爲8)href屬性包括完整的URL,包括主機,即使它不是你使用jQuery輸入/設置的內容。考慮到這一點可能會很棘手(儘管最近的jQuery版本可能已經考慮到了這一點)。你可能應該在init腳本中做一些功能檢測(創建一個虛擬的隱藏鏈接,將其url設置爲「/」,然後檢查.attr(「href」)返回的url是否等於「/」 ) – wheresrhys

+0

+1很好的回答和評論 – amelvin

2

使用jQuery基本上涉及在屏幕上選擇某些東西(例如div),然後對其執行操作(例如替換其文本)。

所以你的jquery需要對你設置的路徑名var做些什麼。

而且你jQuery是不是很有效,你的失蹤到底幾個字符:

$(document).ready(function() { 
    var pathname = window.location.pathname; 
    // select something here and use the pathname, eg: 
    $(".bottom_link").append(pathname); 
}); 

但是,從你的描述我真的不知道你想要的選擇,或者你想要什麼用它做 - 但希望這會讓你開始?