2016-08-04 103 views
0

我想在以下while循環中使用Javascript,但它只適用於第一次迭代。從閱讀其他文章,我有一種感覺,它與ID的事情有關,但我真的不明白。讓Javascript在PHP中工作while循環

繼承人我的代碼:

<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> 

任何建議非常讚賞。

謝謝:)

+4

PHP是服務器端,JavaScript是客戶端 - 兩者不能相互影響......不過,在看了你的代碼,有PHP while循環內沒有JavaScript,因此在問題是誤導!!! ...問題實際上是ID的**必須在HTML頁面中是唯一的** –

回答

0

使用類,而不是身份證。

</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> 
+0

這幾乎是解決方案,謝謝大家的幫助。 – por

0

ID是唯一的:

  • 一個元素只能有一個ID
  • 一頁可以與ID只有一個元素

你可以用」 t使用$('#button')$('#wrapper'),因爲它們不是唯一的。

例如,您可以使用button0,button1button5等作爲ID。例如:

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

您也可以使用類而不是ID,因爲它們不需要是唯一的。

同樣爲list

0

正如在評論中提到的,你需要唯一的ID。 另外,您可以使用類來解決這個問題

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