2017-06-27 24 views
-1

我正在循環所有錨標記以跟蹤該錨標記的ul。不更新jquery的每個循環中的值

我的目標是在匹配的情況下爲ul標籤的類名添加cahnge。

不幸的是在每個循環內部,每次進入條件時,即使我改變了n的值。

var fileName = location.pathname.split("/").slice(-1) 
    //var url = window.location.href; 
    var n = -1; 
    alert(fileName); 
    $("[id$=sample] a").each(function() { 
     n = this.href.indexOf(fileName); 
     if (n != -1) 
     { 
      alert(this.href); 
      alert(n); alert(fileName); 
      n = -1; 
     }   
     console.log(this.href); 
    }); 
+1

什麼是'fileName'的價值,什麼是'href'值?請發佈包含'href'值的HTML以及'fileName'的值。 – Nope

+0

文件名值將作爲我們的網頁名稱,如HomePage.aspx或LoginPage.aspx那些將動態顯示。 –

+0

手動設置'n'的值不會做任何事情,因爲它在下一個循環開始時再次設置爲新值。這個問題有點不清楚,但如果你想在第一場比賽後停止循環,你必須'返回false'。 – JJJ

回答

1

使用filter()和比較<a>location.pathnamepathname簡單多了,直接

$("[id$=sample] a").filter(function() { 
    return this.pathname === location.pathname;  
}).addClass('current-page-class'); 
+0

我需要將類添加到該定位標記的ul。 –

+1

顯示示例html結構。可以改爲'.closest('ul')。addClass('current-page-class');'但是如果你有嵌套ul需要查看html和相關的類以及預期的結果 – charlietfl