簡體   English   中英

如何從PHP中的for循環獲取jquery值?

[英]How to get jquery value from for loop in php?

我正在嘗試提醒單擊div的文本。 有許多具有相同ID的div,如果我單擊第3個或單擊第2個,則想獲得3。 如何使用以下代碼或必須添加哪些內容? 謝謝。

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

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

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

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

只需嘗試使用一個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>

您的代碼中有語法錯誤。 缺少}); 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM