【问题标题】:Getting Javascript to work in PHP while loop让 Javascript 在 PHP 中运行 while 循环
【发布时间】:2016-08-04 10:04:55
【问题描述】:

我正在尝试在以下 while 循环中使用 Javascript,但它仅适用于第一次迭代。通过阅读其他帖子,我感觉它与ID有关,但我并没有真正理解。

这是我的代码:

<html>
<head>


</head>

<body>

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

<style type="text/css">
      #wrapper {
      background: #ccc;
      display:none
      }
</style>

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$('#button').click(function(){
    $('#wrapper').toggle();
})
});//]]> 
</script>

<?php
$x = 5;
while($x > 0)
{
?>
<button id="button">ExP</button>
<div id="wrapper" class="open" style="display: none;">
  <ul id="list">
    <li>Item</li>
  </ul>
</div>
<?php
$x = $x-1;
}
?>

</body>
</html>

非常感谢任何建议。

谢谢:)

【问题讨论】:

  • php 是服务器端,javascript 是客户端 - 两者无法交互......但是,查看您的代码后,php while 循环内没有 javascript,所以这个问题具有误导性!!!...问题实际上是ID的在HTML页面中必须是唯一的

标签: javascript php loops while-loop


【解决方案1】:

使用类而不是 id。

</head>

<body>

<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>

<style type="text/css">
      .wrapper {
      background: #ccc;
      display:none
      }
</style>

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$('.button').click(function(){
    $(this).next('.wrapper').toggle();
})
});//]]> 
</script>

<?php
$x = 5;
while($x > 0)
{
?>
<button class="button">ExP</button>
<div class="wrapper" class="open" style="display: none;">
  <ul id="list">
    <li>Item</li>
  </ul>
</div>
<?php
$x = $x-1;
}
?>

</body>
</html>

【讨论】:

  • 这几乎是解决方案,谢谢大家的帮助。
【解决方案2】:

ID 是唯一的:

  • 一个元素只能有一个 ID
  • 一个页面只能有一个具有该 ID 的元素

您不能使用$('#button')$('#wrapper'),因为它们不是唯一的。

例如,您可以使用button0button1button5 等作为 ID。例如:

<button id="button<?php echo $x; ?>">

您也可以使用类而不是 ID,因为它们不需要是唯一的。

list 也是如此。

【讨论】:

    【解决方案3】:

    正如 cmets 中所述,您需要唯一的 ID。 或者,您可以使用类来解决此问题

    	$(function() {
    		$('.button').on('click', function(e) {
    			e.preventDefault();
    			$(this).next().toggle();
    		});
    	});
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <?php
    	for($i=0;$i<5;$i++) {
    ?>	
    	<button class="button">ExP</button>
    	<div style="display: none;">
    		<ul>
    			<li>Item</li>
    		</ul>
    	</div>
    <?php
    	}
    ?>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      相关资源
      最近更新 更多