简体   繁体   English

PHP:通过do / while循环将第一个元素设置为活动状态

[英]PHP : Setting first element active with do/while loop

Here is my code snippet: 这是我的代码段:

for($x=0;$x<=$flaga1;$x++){ 
$index++;
echo "<div class=\"item\" data-slide-number=".$index.">".$sth."</div>"; 
}

It iterates the code depending on $sth . 根据$sth迭代代码。 But I want to add active class to the first occurence of the code, so it will be: 但是我想在代码的第一次出现时添加active类,因此它将是:

<div class="active item" data-slide-number="0">"sth"</div>
<div class="item" data-slide-number="1">"sth"</div>
<div class="item" data-slide-number="2">"sth"</div>

I'm trying to do something like this, but it doesn't work: 我正在尝试做这样的事情,但是不起作用:

for($x=0;$x<=$flaga1;$x++){ 

$active=0;
$divclass="<div class=\"item\"";

do {
    $divclass="<div class=\"active item\"";
    $active++;
} while ($active<=0);


$index++;
echo "".$divclass." data-slide-number=".$index.">".$sth."</div>"; 

}

As per code submitted by you. 根据您提交的代码。 You can try this. 你可以试试看

for($x=0;$x<=$flaga1;$x++){ 
    $active = "";
    if($x === 0 ) {
        $active = "active";
    }
    $index++;
    echo "<div class=\"item\ <?php echo $active; ?>" data-slide-number=".$index.">".$sth."</div>"; 
}

Or you can do this, as suggested by Niet the Dark Absol. 或者,您也可以按照《黑暗绝对》的建议。

for($x=0;$x<=$flaga1;$x++){ 
   $index++;
   echo "<div class=\"item\ <?php if($x === 0) {echo "active"; } ?>" data-slide-number=".$index.">".$sth."</div>"; 
}

You can also set this up in your for loop definition if you like: 如果您愿意,也可以在for循环定义中进行设置:

for ($x = 0, $a = 'active'; $x < $flaga1; $x++, $a = '') {
    echo "<div class=\"item $a\" data-slide-number=". ++$index .">" . $sth . "</div>\n";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM