Home > Web Front-end > JS Tutorial > How to Dynamically Load Images from a Directory with Non-Consecutive Filenames Using jQuery/JavaScript?

How to Dynamically Load Images from a Directory with Non-Consecutive Filenames Using jQuery/JavaScript?

Susan Sarandon
Release: 2024-11-04 03:21:29
Original
714 people have browsed it

How to Dynamically Load Images from a Directory with Non-Consecutive Filenames Using jQuery/JavaScript?

Dynamically Loading Images from a Directory Using jQuery/JavaScript

Question:

I need to load multiple images from a folder named "images" into my web page. However, the image filenames are not consecutive integers. How can I achieve this using jQuery or JavaScript?

Answer:

The following code snippet will load all the images from the "images" folder into the body of the HTML page:

<code class="javascript">var folder = "images/";

$.ajax({
    url : folder,
    success: function (data) {
        $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpe?g|png|gif)$/) ) { 
                $("body").append( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});</code>
Copy after login

Explanation:

The code starts by creating a folder variable that holds the path to the "images" folder. Then, it uses the jQuery $.ajax() function to load the contents of the folder. The success callback function iterates through the returned data to check if the file extension matches the accepted file types (.jpg, .jpeg, .png, .gif). If it does, the function creates an image element with the appropriate source attribute and appends it to the body of the page.

Note:

  • This code assumes that the Apache server has the Option Indexes feature turned on.
  • For other servers like Express for Node, the 'serve-index' NPM package can be used to allow directory listings.
  • The code can be expanded by adding more accepted file types or by modifying the server configuration to allow directory listings.

The above is the detailed content of How to Dynamically Load Images from a Directory with Non-Consecutive Filenames Using jQuery/JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template