How to load all the images from one of my folder into my web page, using Jquery/Javascript

后端 未结 14 1954
情深已故
情深已故 2020-11-22 10:18

I have a folder named \"images\" in the same directory as my .js file. I want to load all the images from \"images\" folder into my html page using Jquery/Javascript.

<
相关标签:
14条回答
  • 2020-11-22 11:14

    If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:

    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/img", true);
    xhr.responseType = 'document';
    xhr.onload = () => {
      if (xhr.status === 200) {
        var elements = xhr.response.getElementsByTagName("a");
        for (x of elements) {
          if ( x.href.match(/\.(jpe?g|png|gif)$/) ) { 
              let img = document.createElement("img");
              img.src = x.href;
              document.body.appendChild(img);
          } 
        };
      } 
      else {
        alert('Request failed. Returned status of ' + xhr.status);
      }
    }
    xhr.send()
    
    0 讨论(0)
  • 2020-11-22 11:18
    $(document).ready(function(){
      var dir = "test/"; // folder location
      var fileextension = ".jpg"; // image format
      var i = "1";
    
      $(function imageloop(){
        $("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
        if (i==13){
          alert('loaded');
        }
        else{
          i++;
          imageloop();
        };
      });   
    });
    

    For this script, I have named my image files in a folder as 1.jpg, 2.jpg, 3.jpg, ... to 13.jpg.

    You can change directory and file names as you wish.

    0 讨论(0)
提交回复
热议问题