javascript里面的php while循环

use*_*032 0 javascript php jquery

我有这个代码:

<?php
$i=5;
while($i > 0){
echo '
<table width="500px" border="1">
  <tr>
    <td>
    <button id="button">Show comments</button>
    </td>
  </tr>
  <tr>
    <td id="comments" style="display:none;height:300px;width:100%;"></td>
  </tr>
</table>

<script type="text/javascript">
$("#button").toggle(
    function (){
        $("#button").text("Hide Comments");
        document.getElementById("comments").style.display="inline";
    },function (){
        $("#button").text("Show Comments");
        document.getElementById("comments").style.display="none";
    }
);
</script>
<script type="text/javascript" src="jquery.js"></script>
';

$i--;

}
?>
Run Code Online (Sandbox Code Playgroud)

单击"显示注释"按钮时,应显示注释框.它适用于第一个.但它对其他人不起作用.出了什么问题?

Ohg*_*why 5

我只是逃避php解释器并将HTML标记直接打印到页面中.我还将id更改为类,因此我们可以更轻松地重用它们而不需要古怪的附加数字.

<?php
$i=5;
while($i > 0):
?>
    <table width="500px" border="1">
       <tr>
          <td><button class="button" data-clicked="0">Show comments</button></td>
       </tr>
       <tr>
          <td class="comments" style="display:none;height:300px;width:100%;"></td>
       </tr>
    </table>
<?php
$i--;
endwhile;
?>
Run Code Online (Sandbox Code Playgroud)

我不知道the element with an ID节目是什么,但我们只是假设它是按钮.

$(".button").click(function (){
    var $this = $(this);
    if(!$this.data('clicked')){
        $this.text("Hide Comments");
        $this.closest('table').find('.comments').css('display', 'inline');

        $this.data('clicked', 1);
    }else{
        $this.text("Show Comments");
        $this.closest('table').find('.comments').css('display', 'none');

        $this.data('clicked', 0);
    }

});
Run Code Online (Sandbox Code Playgroud)

不要while在php 的循环中打印javascript ,只是将它包含在页面的头部或单独的文件中.

编辑

如下面的评论中所示,在jQuery 1.9中,toggle不再有效,因为您打算使用它,作为一种解决方法,您可以添加一个data attribute按钮,并在每次单击时进行检查.

<button class="button" data-clicked="0">
Run Code Online (Sandbox Code Playgroud)

如您所见,我们添加了新data-clicked属性.

在上面的JavaScript中,您可以看到我们完全改变了它的工作方式.我们执行自己if/else的检查data-clicked状态.