我正在尝试创建一个表,在每一行中都会有一张图片,当单击图片时,会执行一个js函数,表中每一行的条目都会为该行的图片创建一个js脚本。出于这个原因,我在脚本中对图像的id和getElementById使用<?php echo ?>
。在图像的id上使用回显没有问题,但是如果我把它放在getElementById中,js代码就不会被执行。如果我直接写id的编号,假设是getElementById("3")
而不是getElementById("<?php echo $contact['id']; ?>")
,它可以很好地工作,但是如果使用echo,即使加载页面的源代码显示getElementById("<?php echo $contact['id']; ?>")
成功打印为getElementById("3")
,它也无法正常工作
下面是整个表的代码:
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php $contacts = getContacts();
if($contacts->num_rows) {
foreach($contacts as $contact) { ?>
<tr>
<td>
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage("");'>
<script type="text/javascript">
function removeImage() {
document.getElementById("<?php echo $contact['id']; ?>").style.display = "none";
}
</script>
</td>
<td><?php echo $contact['Name']; ?></td>
<td><?php echo $contact['Status']; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
发布于 2020-10-21 16:32:09
在循环时,您会一遍又一遍地重新创建相同的函数,但每个函数都有不同的ID。但是,您不能一遍又一遍地使用相同的名称创建相同的函数。
在您的img上,将removeImage('')
更改为removeImage(this)
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage(this);'>
然后,在循环外部只有一个引用传递给它的元素的函数
function removeImage(el) {
el.style.display = "none";
}
https://stackoverflow.com/questions/64467913
复制