ris*_*shy 46 html javascript jquery image
我在.js文件所在的目录中有一个名为"images"的文件夹.我想使用Jquery/Javascript将"images"文件夹中的所有图像加载到我的html页面中.
因为,图像的名称不是一些连续的整数,我怎么能加载这些图像?
Rok*_*jan 61
同时使用localhost和实时服务器,并允许您扩展允许的文件扩展名的分隔列表:
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 +"'>" );
}
});
}
});
Run Code Online (Sandbox Code Playgroud)
基本上是对Roy的OA的改进
Roy*_*M J 50
使用 :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
Run Code Online (Sandbox Code Playgroud)
如果你有其他扩展,你可以使它成为一个数组,然后逐个使用in_array().
Ps:上面的源代码没有经过测试.
Bar*_*tra 10
这是添加更多文件扩展的方法,在Roy MJ在本页顶部给出的示例中.
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我添加了更多包含.
这是一种方法.涉及做一点PHP.
PHP部分:
$filenameArray = [];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/$file");
}
}
echo json_encode($filenameArray);
Run Code Online (Sandbox Code Playgroud)
jQuery部分:
$.ajax({
url: "getImages.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="'+ filename +'"><br>');
});
}
});
Run Code Online (Sandbox Code Playgroud)
所以基本上你做一个PHP文件,将图像文件名列表作为JSON返回,使用ajax调用获取JSON,并将它们添加/附加到html.您可能希望过滤从文件夹中抓取的文件.
从1开始对php部分提供了一些帮助
如果有兴趣在没有 jQuery 的情况下执行此操作 - 这是目前最受好评的答案的纯 JS 变体(来自此处):
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
189281 次 |
| 最近记录: |