Javascript从php清单中给了我错误的图像名称
所以,我是javascript的初学者,我不知道为什么它给了我错误的图像src。实际上,它只给出了php清单中第一个图像的src 这是我的密码:Javascript从php清单中给了我错误的图像名称,javascript,php,html,image,Javascript,Php,Html,Image,所以,我是javascript的初学者,我不知道为什么它给了我错误的图像src。实际上,它只给出了php清单中第一个图像的src 这是我的密码: <php $files = glob("./images/*.*"); for ($i=0; $i<count($files); $i++) { $image = $files[$i]; $supported_file = array( 'gif',
<php
$files = glob("./images/*.*");
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo '<a target="_self">';
echo '<img src="'.$image .'" onclick="list();" id="img" style="width:100px; margin-right: 10px; margin-bottom: 10px;" class="hover-shadow cursor" alt="Random image">';
echo '</a>';
} else {
continue;
}
}
?>
<script>
function list(){
var pic = document.getElementById("img").src;
alert(pic);
} </script>
函数列表(){
var pic=document.getElementById(“img”).src;
警报(pic);
}
对于页面上的每个元素,id
属性必须是唯一的。这里有一组具有相同id
的图像,代码选择第一个。不要那样做
相反,请使用querySelectorAll
选择图像,例如:
let images = document.querySelectorAll("img");
或者,如果您只想选择一些图像,请在php代码中为它们指定class=“selectable”
属性,然后使用以下方法选择它们:
let images = document.querySelectorAll(".selectable");
这将为您提供页面上所有图像的数组。现在,您可以像这样对其进行迭代:
for (const pic of images) {
alert(pic.src);
}
在任何情况下,页面上都不要有两个或多个元素具有相同的
id
,这只会给您带来问题。您正在使用html id属性获取图像名称,id表示唯一。但在这里,您所有的图像id都是相同的,因此需要为每个元素分配唯一的id。然后像这样更改代码
<?php
$files = glob("./images/*.*");
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'gif',
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
echo '<a target="_self">';
echo '<img src="'.$image .'" onclick="list(this);" id="img" style="width:100px; margin-
right: 10px; margin-bottom: 10px;" class="hover-shadow cursor" alt="Random image">';
echo '</a>';
} else {
continue;
}
}
?>
<script>
function list(img){
var pic = img.src;
alert(pic);
}
</script>
功能列表(img){
var pic=img.src;
警报(pic);
}
图像上甚至不需要有id
。为每个图像指定一个唯一的id
会使代码难以扩展到任意数量的图像。