2013-04-04 26 views
-4

我試圖在點擊一個查看按鈕時顯示div詳細信息,這些按鈕在使用jquery的while循環中顯示,但它只顯示第一條記錄,不顯示其餘記錄,任何人都可以告訴我解決這個問題..Jquery腳本沒有在while循環中運行

下面是示例代碼:

<html> 
<head> 
<script src="js/jquery-1.8.3.min.js"></script> 
<script type="text/javascript"> 
$(function(){ 
    $('#view').click(function() { 
    var user=$('#user').text(); 
     alert(user); 
    }); 
    }); 
</script> 
<style type="text/css"> 
#content div{display:inline-block;} 
</style> 
</head> 
<body> 
<?php 
$i=0; 
while($i<5) 
{ 
?> 
<div id="content"> 
<div id="user">Street(<?=$i+1?>)</div> 
<div id="view" style="color:green;cursor:pointer;">View</div> 
</div> 
<?php 
$i++; 
} 
?> 
</body> 
</html> 
+0

多個唯一的ID是不允許的。切換到課程。 – ahren 2013-04-04 06:05:44

+0

ID必須是唯一的。改爲使用班級。 – Barmar 2013-04-04 06:05:46

回答

2

id意味着是唯一的(使用# jQuery中表示)。嘗試使用class(在Jquery中使用.表示)。

<div class="content"> 
<div class="user">Street(<?=$i+1?>)</div> 
<div class="view" style="color:green;cursor:pointer;">View</div> 
</div> 

和JavaScript:

<script type="text/javascript"> 
    $(function(){ 
     $('.view').click(function() { 
      var user=$(this).parent().find('.user').text(); 
      alert(user); 
     }); 
    }); 
</script> 
+0

我試過了我們的代碼,但是我得到了空的結果作爲警報 – lalith222 2013-04-04 06:14:03

+0

@ lalith222我更新了javascript部分,看它是否有效。 – Tushar 2013-04-04 06:19:33

+0

它現在正在工作 – lalith222 2013-04-04 06:23:02

0

您已設置ID = 「用戶」,所以你會得到5周div的使用相同ID,所以很明顯這將只打印第一個。所以使用類。

而獲得當前元素的值,使用

$(this).text(); 
0

嘗試這個公司對你的作品..

<html> 
<head> 
<script src="js/jquery-1.8.3.min.js"></script> 
<script type="text/javascript"> 
$(function(){ 
    $('.view').click(function() {   
     var id = $(this).attr('id'); 
     var user=$('#user'+id).text(); 
     alert(user); 
    }); 
    }); 
</script> 
<style type="text/css"> 
#content div{display:inline-block;} 
</style> 
</head> 
<body> 
<?php 
$i=0; 
while($i<5) 
{ 
?> 
<div id="content"> 
<div class="user" id="user<?php echo $i+1;?>">Street(<?php echo $i+1;?>)</div> 
<div class="view" id="view<?php echo $i+1;?>" style="color:green;cursor:pointer;">View</div> 
</div> 
<?php 
$i++; 
} 
?> 
</body> 
</html>