将元素 ID 从 PHP 传递给 Javascript


Passing an element id from PHP to Javascript

我从我的mysql数据库中有一些数据。我使用 foreach 循环在表中显示数据,如下所示

<table> 
foreach($students as $row):?>
        <tr><td><i id="expand<?php echo $row['student_id'];?>" class="myclass fa fa-plus-square"></i></td>
        <td><?php echo $i; $i++;?></td>
            <td><?php echo $row['roll'];?></td>
            <td style="text-align:center;"><img src="<?php echo $this->crud_model->get_image_url('student',$row['student_id']);?>" class="img-circle" width="50" /></td>
            <td><?php echo $row['name'];?></td>
            <td><?php echo $row['address'];?></td>
            <td><?php echo $row['phone'];?></td></tr></table>

我在 Javascript 中还有一个点击事件函数,如下所示

$('#expand').click(function(){
    $('#dev').toggleClass('hidden');
});

这是我想隐藏并在点击事件时显示。请注意,此行包含学生ID为$row['student_id']的学生的数据

 <tr id="dev<?php echo $row['student_id'];?>" class="hidden">
            <td colspan="7">
            <table>
            <tr><td>Phone Number is <?php echo $row['phone'];?></td></tr>
            </table>
            </td>
            </tr>

我想将元素 id 从 php 传递给 javascipt,以便在单击 id 展开时它将执行一些功能,例如显示或隐藏

谢谢。

你没有一个名为 "expand"id,你有这个:

id="expand<?php echo $row['student_id'];?>"

假设$row['student_id']不为空(至少对于多个记录,它不应该为空,因为id必须是唯一的),那么id就不会"expand"。 但是,它将"expand"开始。 因此,您可以选择:

$('[id^="expand"]').click(function(){
    // handle the click event here
});

这会将相同的click处理程序附加到每个匹配的项目,这是页面上id"expand" 开头的任何元素。 请注意,处理程序将为每个元素执行相同的操作,因此您当前的逻辑针对单个元素(id"dev")来切换其可见性。 因此,目前,每次单击都会显示/隐藏相同的元素。 您可能不想要该功能,但这并不完全包含在问题中。 (标记中没有#dev元素,因此不完全清楚您希望它的行为方式。

编辑

有多种

方法可以定位要显示/隐藏的元素。 无需更改标记,您可能只需获取id的数字部分并使用它来构建目标id。 可能是这样的:

$('[id^="expand"]').click(function(){
    var idNumber = $(this).attr('id').replace(/expand/g, '');
    $('#dev'+id).toggleClass('hidden');
});

感谢所有参与者

但特别感谢@david&@deacs

我已经让它工作如下

$('[id^="expand"]').click(function(){
var id = $(this).attr('data-id');
$('#dev'+id).toggleClass('hidden');
});

向元素添加属性。

<i id="expand<?php echo $row['student_id'];?>" data-id="<?php echo $row['student_id'];?>" class="myclass fa fa-plus-square"></i>

在类而不是 id 上调用函数,因为有多个元素。

$('.myclass').click(function(){
  var id = $(this).attr('data-id');
  $('#dev-'+id).toggleClass('hidden'); // apply proper logic here.
});
您也可以

在选择器中使用.myclass,然后从从attr()检索的id中删除字符串expand

$('.myclass').click(function(){
    var id = $(this).attr('id').replace('expand','');
    $('#dev'+id).toggleClass('hidden');
});