如何从php中的for循环中获取jquery值

How to get jquery value from for loop in php?

本文关键字:获取 jquery 循环 for php 中的      更新时间:2023-09-26

我试图在单击时提醒处于for循环中的div的文本。有很多div都有相同的id,如果我点击第三个,我想得到3个,或者当点击第二个时得到2个。我如何用以下代码制作它,或者我必须添加什么?非常感谢。

<? for($i=0; $i<5; $i­­++) { ?>
    <div id="abc"><? echo $i ?></div>
<? } ?>
<script>
    $(function() {
        $("#abc").click(function() {
            var thevar= $("#abc").text();
            alert (thevar);
        }
</script>

只需尝试在循环中使用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。因此CCD_ 3总是返回匹配选择器中第一个元素的值。而是使用abc作为类。要在当前上下文中引用元素,请使用$(this):

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

您的代码中存在语法错误。缺少});。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>