var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
$("ul").find("a[href=filename]").addClass('active');
with an ul in my header.php:
<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>
I spent hours with this. I just can't add a class to an anchor tag, based on the site i am currently on.
答案 0 :(得分:1)
试试这个:
$uri=$_SERVER['REQUEST_URI'];
通过这个,您可以获得URI,例如&#34; /index.php &#34;,现在您需要将其与标记中的网址进行比较。即使我推荐使用JS / jQuery,例如:
var current_path_url=window.location.pathname;
$('a[href="'+current_path_url+'"]').parent().addClass('active');
答案 1 :(得分:1)
变量不会在引用的字符串中扩展,您必须使用连接(除非您想使用ES6模板文字,但旧版浏览器不支持它们)。
$("ul > li > a[href=" + filename + "]").addClass('active');