Javascript从php列表中给我错误的图像名称

时间:2018-12-08 10:16:18

标签: javascript php html image

所以,我是javascript的新手,我不知道为什么它给我错误的图像src。实际上,它只是给我php列表中第一张图片的源代码。

这是我的代码:

<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>

2 个答案:

答案 0 :(得分:0)

页面上每个元素的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的元素,这只会给您带来麻烦。

答案 1 :(得分:0)

您正在使用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>