2

I have a menu like this:

<div id="blahblah" style="blahblah">
<a href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/gallery"><img style="blahblah" src="blahblahblahblah"></a>
<a href="http://domain.com/folder/dontknow"><img style="blahblah" src="blahblahblahblah"></a>
</div>

I'd like to have something that automatically adds a class="current" to the page I'm currently in. Links (as you can see in the code above) are like domain.com/folder/biography or domain.com/folder/contacts, so without .php/.html, etc.

I tried with:

<div id="blahblah" style="blahblah">
<a <?php if (strpos($_SERVER['PHP_SELF'], 'biography')) echo 'class="current"';?> href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
<a <?php if (strpos($_SERVER['PHP_SELF'], 'contacts')) echo 'class="current"';?> href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
...
...
</div>

But it doesn't work... the solution with strops seems viable, probably I'm doing it wrong.. :P

4

3 回答 3

3

你应该:

  1. 检查strpos()with的结果!== false
  2. 使用$_SERVER['REQUEST_URI']而不是$_SERVER['PHP_SELF'].
  3. 将代码包装在一个函数中。

像这样的东西:

<?php
function get_current($name) {
  if (strpos($_SERVER['REQUEST_URI'], $name) !== false)
    echo 'class="current"';
}
?>

<div id="blahblah" style="blahblah">
  <a <?php get_current('biography') ?> href="http://domain.com/folder/biography"><img style="blahblah" src="blahblahblahblah"></a>
  <a <?php get_current('contacts') ?> href="http://domain.com/folder/contacts"><img style="blahblah" src="blahblahblahblah"></a>
  ...
  ...
</div>
于 2012-06-04T16:35:49.260 回答
1

如果位置为 0,那么它将在 PHP 中评估为 FALSE。您应该专门检查返回值,即 >= 0。

于 2012-06-04T16:25:39.990 回答
1

而不是strpos(),你可以试试这个:

<?php $current = basename($path, ".php"); ?>

<a href="blahblah"<?php if ($current == 'biographies') echo ' class="current"'; ?> />

$current是当前文件的名称,不带.php扩展名。

于 2012-06-04T16:33:42.280 回答