jQuery在菜單上添加class .active我有一個(gè)問題。我想在相關(guān)頁面打開時(shí)在項(xiàng)目菜單上添加“活動(dòng)”類。菜單很簡單:<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中,我需要檢查網(wǎng)址是否為www.xyz.com/other/link1/如果是這個(gè)我想添加第一類是link1的'a'元素。我正在嘗試很多解決方案,但沒有任何效果。
3 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
點(diǎn)擊這里查看jsFiddle中的解決方案
你需要的是你需要獲得所提到的window.location.pathname,然后從中創(chuàng)建regexp并根據(jù)導(dǎo)航hrefs進(jìn)行測試。
$(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貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
對(duì)我來說更簡單的方法是:
var activeurl = window.location;$('a[href="'+activeurl+'"]').parent('li').addClass('active');
因?yàn)槲业逆溄愚D(zhuǎn)到絕對(duì)網(wǎng)址,但如果您的鏈接是相對(duì)的,那么您可以使用:
window.location**.pathname**
添加回答
舉報(bào)
0/150
提交
取消