2017-07-31 127 views
-1
var url = window.location.pathname; 
var filename = url.substring(url.lastIndexOf('/')+1); 
$("ul").find("a[href=filename]").addClass('active'); 

在我的header.php的UL:如何在php中使用特定的href將類添加到<a>?

<li><a href="index.php">Főoldal</a></li> 
<li><a href="gallery.php">Galéria</a></li> 
<li><a href="games.php">Játékok</a></li> 
<li><a href="contacts.php">Elérhetőségeink</a></li> 
<li><a href= "about.php">Rólunk</a></li> 

我花了幾個小時與此有關。根據我目前所在的網站,我無法將一個類添加到錨標記中。

+1

讓我們知道了什麼是的console.log的'輸出(文件名);'變種文件名= url.substring後'PH_1PH_1廣告它(url.lastIndexOf( '/')+ 1);'和檢查你的瀏覽器控制檯,並讓我們知道 –

+0

做'$(「ul> li> a [href ='」+ filename +「'」)「)。addClass('active')'可能會起作用,儘管最好添加類因爲PHP知道哪一部分更準確(例如,如果你打算使用重寫等) – apokryfos

回答

1

試試這個:

$uri=$_SERVER['REQUEST_URI']; 

有了這個,你得到的URI,如「的index.php」,現在你需要將它與您的代碼中的URL進行比較。雖然我推薦使用JS/jQuery的,如:

var current_path_url=window.location.pathname; 

$('a[href="'+current_path_url+'"]').parent().addClass('active'); 
1

不會擴展變量引用字符串,你必須使用級聯(除非你想使用ES6模板文字,但舊的瀏覽器不支持他們)。

$("ul > li > a[href=" + filename + "]").addClass('active'); 
相關問題