javascript里面的php while循环
我有这个代码:
0){ echo '
$("#button").toggle( function (){ $("#button").text("Hide Comments"); document.getElementById("comments").style.display="inline"; },function (){ $("#button").text("Show Comments"); document.getElementById("comments").style.display="none"; } ); '; $i--; } ?>
单击show comments按钮时,应显示注释框。 它适用于第一个。 但它对其他人不起作用。出了什么问题?
我只是逃避PHP解释器并将HTML标记直接打印到页面中。 我还将id更改为类,因此我们可以更轻松地重用它们而不需要古怪的附加数字。
0): ?>
我不知道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); } });
不要在php中的while
循环中打印javascript,只是将它包含在页面的头部或单独的文件中。
编辑
如下面的评论中所示,在jQuery 1.9中, toggle
不再有效,因为您打算使用它,作为解决方法,您可以向按钮添加data attribute
,并在每次单击时进行检查。
如您所见,我们添加了新的data-clicked
属性。
在上面的JavaScript中,您可以看到我们已经彻底改变了它的工作方式。 我们执行自己的if/else
来检查data-clicked
状态。
分离代码,标记和样式声明通常是一种很好的做法。 作为一种风格问题,我更喜欢编号ID。 我发现它们有助于调试。 ymmv我也喜欢动画变化,以便人们可以更轻松地跟随变化。
Button Testing 1 2 3 $j = 0; while ($j < 5 ) { ?> J = = $j ?>
$j++; } ?>