jQuery在菜單上添加class .active我有一個問題。我想在相關頁面打開時在項目菜單上添加“活動”類。菜單很簡單:<div class="menu"><ul><li><a href="~/link1/">LINK 1</a><li><a href="~/link2/">LINK 2</a><li><a href="~/link3/">LINK 3</a></ul></div>在jQuery中,我需要檢查網址是否為www.xyz.com/other/link1/如果是這個我想添加第一類是link1的'a'元素。我正在嘗試很多解決方案,但沒有任何效果。
3 回答
慕后森
TA貢獻1802條經驗 獲得超5個贊
點擊這里查看jsFiddle中的解決方案
你需要的是你需要獲得所提到的window.location.pathname,然后從中創建regexp并根據導航hrefs進行測試。
$(function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
// now grab every link from the navigation
$('.menu a').each(function(){
// and test its normalized href against the url pathname regexp
if(urlRegExp.test(this.href.replace(/\/$/,''))){
$(this).addClass('active');
}
});});
楊__羊羊
TA貢獻1943條經驗 獲得超7個贊
對我來說更簡單的方法是:
var activeurl = window.location;$('a[href="'+activeurl+'"]').parent('li').addClass('active');因為我的鏈接轉到絕對網址,但如果您的鏈接是相對的,那么您可以使用:
window.location**.pathname**
- 3 回答
- 0 關注
- 943 瀏覽
相關問題推薦
添加回答
舉報
0/150
提交
取消
