douhuan1950 2012-02-17 16:56
浏览 47
已采纳

单击foreach循环显示/隐藏xml内容

I'm frustrated with this. What I am trying to code is a simple xml reader that allows user to choose which data is shown or hidden.

First this code shows the titles of the xml-file and when user clicks a title, date and time should be shown under the title.

The problem is that no matter which title is clicked, it only shows/hides the date-time of the first title under the first title.

<script type="text/javascript">
   function toggle(element) {
   document.getElementById(element).style.display =     
(document.getElementById(element).style.display == "none") ? "" : "none";
}
</script>

<?php
$doc = simplexml_load_file('data.xml');
if($doc == TRUE){
foreach($doc->channel->item as $child){
   $title = $child->title;
   echo '<table>';
   echo '<tr>';
   echo '<td><a href="javascript:toggle(\'shit\')">'.$title.'</a></td></tr>';
   echo '<tr id="shit" style="display: none;">';
   echo '<td>';
   echo date("d.m.Y H:i", strtotime($child->pubDate));
   echo '</td></tr>';
   echo '</table>';
}
}
?>
  • 写回答

3条回答 默认 最新

  • dongyuan2388 2012-02-17 16:59
    关注

    As the others said, you need to have a unique id per element (that you want to get a reference to). The simplest way is to just add a counter to the name you choose, in this case "shit", here's the modified version:

    <script type="text/javascript">
       function toggle(num) {
       document.getElementById("shit" + num).style.display =     
    (document.getElementById("shit" + num).style.display == "none") ? "" : "none";
    }
    </script>
    
    <?php
    $doc = simplexml_load_file('data.xml');
    if($doc == TRUE){
    $1 = 0;
    foreach($doc->channel->item as $child){
       $title = $child->title;
       echo '<table>';
       echo '<tr>';
       echo '<td><a href="javascript:toggle(\''.$i.'\')">'.$title.'</a></td></tr>';
       echo '<tr id="shit'.$i.'" style="display: none;">';
       echo '<td>';
       echo date("d.m.Y H:i", strtotime($child->pubDate));
       echo '</td></tr>';
       echo '</table>';
    }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题