[英]If statement in PHP For loop not working
I'm trying to add the CSS class "selected" to the first accordionButton div created. 我正在尝试将CSS类“ selected”添加到创建的第一个AccordionButton div中。 Why doesn't this work?
为什么不起作用?
// Create nav from database
$chapter_array = get_chapter_names();
for ($i=0; $i < sizeof($chapter_array); $i++) {
if($i == 0) {
$selected = 'selected';
}
echo '<div class="accordionButton '.$selected.'">'.$chapter_array[$i].'</div>';
$page_id_array = get_page_ids($i);
echo '<div class="accordionContent">';
for ($j=0; $j < sizeof($page_id_array); $j++) {
$page_name = get_page_name($page_id_array[$j]);
echo '<a href="?page_id='.$page_id_array[$j].'">'.$page_name.'</a><br />';
}
echo '</div>';
}
You never set $selected
back after the first div so this adds that class to every div, because $selected
always contains the string 'selected'
. 您永远不会在第一个div之后设置
$selected
,因此这会将类添加到每个div中,因为$selected
始终包含字符串'selected'
。
You can set it to the empty string before your if statement: 您可以在if语句之前将其设置为空字符串:
$selected = '';
if($i == 0) {
$selected = 'selected';
}
If you like this better you can also write that as a nice ternary expression: 如果您更好地喜欢它,还可以将其编写为一个不错的三元表达式:
$selected = $i == 0 ? 'selected' : '';
Declare $selected outside of the loop too: 在循环外也声明$ selected:
$chapter_array = get_chapter_names();
$selected = '';
for ($i=0; $i < sizeof($chapter_array); $i++) {
if($i == 0) {
$selected = 'selected';
}
echo '<div class="accordionButton '.$selected.'">'.$chapter_array[$i].'</div>';
$page_id_array = get_page_ids($i);
echo '<div class="accordionContent">';
for ($j=0; $j < sizeof($page_id_array); $j++) {
$page_name = get_page_name($page_id_array[$j]);
echo '<a href="?page_id='.$page_id_array[$j].'">'.$page_name.'</a><br />';
}
echo '</div>';
}
Also, this is a lil bit prettier (: 此外,这是一点点的漂亮(:
$selected = $i == 0 ? 'selected' : '';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.