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