【问题标题】:How to pull images from directory without server [duplicate]如何在没有服务器的情况下从目录中提取图像[重复]
【发布时间】:2014-08-07 09:16:24
【问题描述】:

我有一个图片滑块网页。那里有许多图像标签。因此,每当我想在滑块中添加图像时,每次我都在 html 中添加标签。是否可以不添加图像标签。

<div id="slideshow" class="slideshow">


   <img src="images/1.jpeg" width="620" height="320" />
   <img src="images/2.jpeg" width="620" height="320" />
   <img src="images/3.jpeg" width="620" height="320" />
   <img src="images/4.jpeg" width="620" height="320" />

</div>

如果我想添加新图像,我必须添加新的 img 标签。是否可以在 html 中不添加 &lt;img&gt; 的情况下添加图像??

我已经尝试过使用 jquery。我没有从文件夹中获取图像。

  $('<img />')
    .attr('src', 'images/')
    .appendTo('#div3')

我们如何解决这个问题?

【问题讨论】:

  • 分享您的 javascript 代码尝试...
  • 您是否有充分的理由不想添加新的img 标签?你知道你可以通过 JS 动态地做到吗?
  • @RakeshShetty 该链接将仅处理 linux 平台不支持的 activex obect
  • @TJ :我分享了有问题的 jquery cod
  • @LcSalazar 是的,但是我们如何从 js 中的目录中获取图像

标签: javascript jquery html css image


【解决方案1】:

我认为在Is there a way to return a list of all the image file names from a folder using only Javascript? 中一切都准备好了

$.ajax({
 url: "http://yoursite.com/images/",
  success: function(data){
    $(data).find("td > a").each(function(){
       // will loop through 
       alert("Found a file: " + $(this).attr("href"));
   });
 }
 });

【讨论】:

  • 我没有使用任何服务器。只有 html,js,jquery
  • 你在哪里保存图像在 url 中给出该路径
  • 我用过但没有显示任何东西。文件路径是 file:///home/indiapc_dev_new1/my_project/jeevan%28image_slider%29/images/
  • 相对路径不起作用。如果服务器不存在,它将如何采用相对路径..我给了 url:"file://images/", url="images/"...都 r 不工作
  • 如果你有 mainFolder/ ,因为你的代码在 mainfolder/yourcode.js 和图像文件夹作为 mainfolder/images 然后将路径作为 "images/ " 或 "../images" 试试这个
【解决方案2】:

利用 jQuery 库。

您可以使用以下内容:

$("#slideshow").append("<img src=\"images/5.jpeg\" />")

或以下(更好的可读性)

var newImg = $("<img />").attr("src","images/5.jpeg").css({"width":"620px","height":"320px"})
$("#slideshow").append(newImg);

现在要动态检索目录中图像的文件列表,您将需要某种服务器端语言(php、ruby、python、c#、nodejs 等),因为 Javascript 无法访问服务器的文件系统。如果没有服务器端语言,您可以创建一个 JSON 或 XML 文件,然后由您的 Javascript 读取,这样您就不会更改 html 而是快速添加新项目。

{"images": [
  {"src" : "images/5.jpeg",
   "css": {
         "width" : "620px",
         "height" : "320px"
    }
  }, {
   "src" : "images/6.jpeg",
   "css": {
         "width" : "620px",
         "height" : "320px"
  }
]}

然后执行以下操作来检索您创建的 json 文件:

$.getJSON("images.json",function(data){
  $.each(data,function(i,image){
    var newImg = $("<img />").attr("src",image.src).css(image.css);
    $("#slideshow").append(newImg);
  });
});

这是未经测试的代码,可以通过一些调整来开始工作。

资源也可以查看以获取更多信息。

stackoverflow:jquery loop on Json data using $.each

jquery-api:http://api.jquery.com/jquery.getjson/

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2021-07-17
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2011-02-28
    • 2014-04-10
    相关资源
    最近更新 更多