2014-04-23 38 views
0

我試圖提醒在點擊時處於for循環的div文本。有很多具有相同ID的div,如果點擊第二或第二點擊時我想獲得3。我如何使用下面的代碼或我必須添加到它?謝謝。如何從php for循環獲取jquery值?

<? for($i=0; $i<5; $i­­++) { ?> 
    <div id="abc"><? echo $i ?></div> 
<? } ?> 

<script> 
    $(function() { 
     $("#abc").click(function() { 
      var thevar= $("#abc").text(); 
      alert (thevar); 
     } 
</script> 
+1

id應該是唯一的..! :/ –

+0

你錯過了幾個右括號('); });')在腳本的末尾。 – Cerbrus

回答

1

剛剛嘗試使用class而不是使用id是循環內,

<? for($i=0; $i<5; $i­­++) { ?> 
<div class="abc"><? echo $i ?></div>  
<? } ?> 

<script> 
$(function() { 
    $(".abc").click(function() 
    { 
     var thevar= $(this).text(); 
     alert (thevar); 
    }); 
}); 
</script> 
+1

謝謝..它的工作。 –

1

你應該在頁面上有唯一的ID。由於這個$("#abc").text()總是返回匹配選擇器中第一個元素的值。而是使用abc作爲類。並指在當前上下文元素,使用$(this)

var thevar=$(this).text(); 
+0

@downvoter關心評論。 –

1

您在代碼中有語法錯誤。缺少});。 Id應該是唯一的。

<? for($i = 0;$i<5;$i++) { ?> 

<div class="abc"><? echo $i ?></div> //change 

<? } ?> 

<script src="http://code.jquery.com/jquery-latest.min.js" 
     type="text/javascript"></script> 



<script> 
$(function() { 
$(".abc").click(function() 
{ 
var thevar= $(this).text(); //change 
alert (thevar); 
});//was missing 
});//was missing 
</script>