问题
I have an include file that includes the header and footer of my site. But in the header I use an active class to let the menu-item change when on that page. How can you achieve this using one include file? With PHP?
I found this:
index.php
<?php $page == 'one'; include('includes/header.php'); ?>
header.php
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="contact.php">Contact</a>/</li>
But it's not changing, when I just used the class on every page seperately, it worked.
回答1:
Index.php
<?php $page = 'one'; include('includes/header.php'); ?>
$page = 'one'. "==" is a comparison operator http://www.php.net/manual/en/language.operators.comparison.php
Header.php
<li><a href="#"<?php if($page == 'one'){ echo ' class="active"';}?>>LINK</a></li>
I think is more clean like that
回答2:
just move the echo
to correct place(s), because your syntax is not correct
Like this;
<li>
<a
<?php
echo( $page == 'one' ? "class='active'" : "");
?>
href="contact.php">Contact</a>
/
</li>
And also you should correct this in include.php
$page = 'one';
with single "=" sign
回答3:
<?php
$page = 'one';
include('includes/header.php');
?>
$page =1; not $page == 1; because it is assignment of a variable.
Rest of the code is fine.
来源:https://stackoverflow.com/questions/21254404/class-active-when-on-page-using-php