如何将文件夹中的多个html文件加载到div中 [英] How can I load multiple html files from a folder into a div

查看:134
本文介绍了如何将文件夹中的多个html文件加载到div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个文件夹"../cars/",其中包含多个html文件,我想将所有这些文件加载​​到另一个html文件中.

Say I've got folder "../cars/" that holds multiple html files, and I want to load all of these files into another html file.

我可以通过执行以下操作轻松解决此问题:

I could easily go about this by doing something like:

$(document).ready(function (){
     $("#all_cars").load("../cars/civic.html");
     $("#all_cars").load("../cars/durango.html");
     $("#all_cars").load("../cars/mustang.html");
     $("#all_cars").load("../cars/r8.html");
     ... and so on
});

但是我想以更复杂的方式做到这一点.我也不想将文件名编码到我的js文件中.我希望能够从文件夹中删除文件,然后再加载它.有没有办法我可以获取cars文件夹中的所有文件名并循环遍历它们以进行加载?

But I'd like to do this in a more sophisticated manner. I also don't want to have to code the file names into my js file. I'd rather be able to remove the file from the folder and now have it load anymore. Is there a way I could get all the filenames in the cars folder and loop over them to load?

这类的:

foreach(cfn in carsFilesNames){
     $("#all_cars").load("../cars/" + carsFileNames);
}

推荐答案

希望这是您想要的:

$.each([
    'civic.html',
    'durango.html',
    'mustang.html',
    'r8.html'
], function(i,a){
    $("#all_cars").load("../cars/" + a);
});

$.each将遍历数组.


如果希望自动获取目录中的所有文件并列出它们,并且Web服务器上装有PHP,请添加一个名为carindex.php的文件,并将其内容设置为:


If you wish to automatically get all files in the directory and list them, and you have PHP on your web server, add a file called carindex.php, set it's content to:

<?php

print json_encode(scandir('PATH/TO/cars/', 1));

?>

然后在客户端:

$.get('/carindex.php', function (a) {
    a.forEach(function (b) {
        $("#all_cars").load("../cars/" + b);
    });
});

这篇关于如何将文件夹中的多个html文件加载到div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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