开发者

Code to detect current page

Is there a php or javascript code that can detect the current user's page and then add <a class="active"> to an item in a开发者_JS百科 ul (my menu). I include my menu in my pages with PHP include so making change is easy; I only have to edit it once. But, with that method, I can't individually set each page to have a class="active". How can I do this?


You several options, e.g.,

  • The part that handles navigations can read the request URI directly. This can be done by reading $_SERVER['REQUEST_URI'] (don't forget this may include the query string).
  • At some point, you must know what page you're on, because you decide which content you display based on that. You can define a function that handles the navigation markup and pass it the name of the current page so that it knows which one it is.


If I'm understanding your question correctly, what I usually do is set a variable before I include the header, like

$current = "home";

And then in the header I'd have an if statement in each link

<a href="/home" <?php if ( $current == "home" ) { echo "class='active'" } ?>>Home</a>

Could be ways to improve it, but it's simple if your menu isn't too big.


In PHP, you can look at the value of $_SERVER['REQUEST_URI'].

In JavaScript, you can examine window.location.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜