doudi4014 2011-06-29 21:39
浏览 22
已采纳

php变量没有返回预期的内容

I have an unordered list that's being generated from a database. Depending on the value of one of the returned fields, the li tag's class should be set to different values. Unfortunately they're all returning "inactive". I know this must be something simple, but I've been staring at it for hours and am just not seeing it.

Here's the code:

<ul class="tabs">
   <? foreach ($tracks AS $track) {
    $active = (strtolower($track->shortname === 'dpp')) ? ' class="active"' : 'class="inactive"';
    echo "<p>".strtolower($track->shortname). " is ".$active."</p>"; ?>
    <li <?= $active; ?>><a href="#<?= strtolower($track->shortname); ?>"><?= $track->name; ?></a></li>
   <? } ?>
</ul>

Here's what is actually getting printed:

<ul class="tabs"> 
    <p>dpp is class="inactive"</p>  <li class="inactive"><a href="#dpp">Digital Path to Purchase</a></li> 
    <p>cre is class="inactive"</p>  <li class="inactive"><a href="#cre">Fueling Creativity</a></li> 
</ul> 

It's obvious that the first one is returning $track-shortname of dpp, so why is the $active variable not getting set to "class=active"?

  • 写回答

3条回答 默认 最新

  • dqqxkq4047 2011-06-29 21:43
    关注

    You've made an error in the expression where you check the shortname:

    $active = (strtolower($track->shortname === 'dpp')) ? ' class="active"' : 'class="inactive"';
                         ^                           ^
    

    You most certainly only want to put it around $track->shortname:

    $active = (strtolower($track->shortname) === 'dpp') ? ' class="active"' : 'class="inactive"';
                         ^                 ^
    

    Otherwise you tried to lowercase a boolean value which is either true or false but in your case it looks to always be false, hence the inactive CSS class.

    BTW, you can spare another pair:

    $active = strtolower($track->shortname) === 'dpp' ? ' class="active"' : 'class="inactive"';
             ^                                       ^
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan