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

后端 未结 14 2175
情深已故
情深已故 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:13

    Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:

    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( "" );
                } 
            });
        }
    });
    

    NOTICE

    Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index

    If the files you want to get listed are in /images than inside your server.js you could add something like:

    const express = require('express');
    const app = express();
    const path = require('path');
    
    // Allow assets directory listings
    const serveIndex = require('serve-index'); 
    app.use('/images', serveIndex(path.join(__dirname, '/images')));
    

提交回复
热议问题