如何使用 Jquery/Javascript 将我的一个文件夹中的所有图像加载到我的网页中 [英] How to load all the images from one of my folder into my web page, using Jquery/Javascript

查看:24
本文介绍了如何使用 Jquery/Javascript 将我的一个文件夹中的所有图像加载到我的网页中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 .js 文件所在的目录中有一个名为images"的文件夹.我想使用 Jquery/Javascript 将images"文件夹中的所有图像加载到我的 html 页面中.

既然图片的名字不是一些连续的整数,我应该如何加载这些图片?

解决方案

在本地主机和实时服务器上都没有问题,并允许您扩展允许的文件扩展名的分隔列表:

var folder = "images/";$.ajax({网址:文件夹,成功:功能(数据){$(data).find("a").attr("href", function (i, val) {if( val.match(/.(jpe?g|png|gif)$/) ) {$("body").append("" );}});}});

注意

Apache 服务器默认启用 Option Indexes - 如果您使用其他服务器,例如 Express for Node,您可以使用此 NPM 包使上述工作:https://github.com/expressjs/serve-index

如果您要列出的文件在 /images 中而不是在 server.js 中,您可以添加如下内容:

const express = require('express');const app = express();const path = require('path');//允许资产目录列表const serveIndex = require('serve-index');app.use('/images', serveIndex(path.join(__dirname, '/images')));

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.

Since, names of images are not some successive integers, how am I supposed to load these images?

解决方案

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( "<img src='"+ folder + val +"'>" );
            } 
        });
    }
});

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')));

这篇关于如何使用 Jquery/Javascript 将我的一个文件夹中的所有图像加载到我的网页中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆