php - php while 循环中的 javascript

标签 php javascript 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--;

}
?>

当单击“显示评论”按钮时,应该会显示评论框。它适用于第一个。但对其他人不起作用。出了什么问题?

最佳答案

我只是逃避 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;
?>

我不知道 ID 为 show 的元素是什么,但我们假设它是按钮。

$(".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);
    }

});

不要在 php 的 while 循环中打印该 javascript,只需将其包含在页面的头部或单独的文件中即可。

编辑

如下面的评论所示,在 jQuery 1.9 中,toggle 不再按照您的意图使用它,作为解决方法,您可以添加一个 data 属性 到按钮,并在每次单击时检查它。

<button class="button" data-clicked="0">

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

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

关于php - php while 循环中的 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680482/

相关文章:

php - MacOs 中的 Docker 非常慢

javascript - 为什么Ajax请求改变参数值?

php - 无法从 Linux 发送邮件,但与 Windows 完美配合

javascript - Django 中的 AJAX 调用完成时未调用成功函数 "Add to Favourites Button"

javascript - 如何使用 ParseServerOptions

php - Android - Craigslist 通知应用程序,可将新帖子发送到我的电子邮件/短信/RSS

javascript - 为什么 Javascript 中的变量赋值运算符优先级会以其他方式工作

javascript - 意外 session 破坏

javascript - 如何限制输入字段仅包含数字值?

JQuery - 使用 load() 将页面加载到 div - 如何卸载?