簡體   English   中英

使用JavaScript將txt文件加載到div

[英]Load txt file to div using JavaScript

現在我有使用此代碼的JavaScript函數,但需要幫助,用存儲在txt文件中的圖像鏈接替換div,所以我不想更改<div id="GALLERY">只是存儲鏈接的數據在txt文件中逐行顯示。 對於pics.txt加載到div中的每一行,還需要幫助在開始處添加'<img src="' ,並在末尾添加">

txt文件稱為pics.txt

<div id="GALLERY">
</div>

這是pics.txt的樣子

http://www.clearviewarts.com/thumbnails/Pug.jpg
http://www.clearviewarts.com/thumbnails/BabyIndy.jpg
http://www.clearviewarts.com/thumbnails/CanusAngelicus.jpg
http://www.clearviewarts.com/thumbnails/Puppy%20In%20Basket.jpg
http://www.clearviewarts.com/thumbnails/Wagner-edit1.jpg
http://www.clearviewarts.com/thumbnails/HarlequinDane.jpg

將這些鏈接放在JSON格式的文件中,以便您輕松解析它。

假設您已經了解AJAX。 因此,使用AJAX加載此文件格式服務器。

這是jQuery的代碼示例。

//urls.json is the file used to store those links
$.getJSON('urls.json', function(data) {
   //just Google how to parse JSON with javascript. It is quite easy 
   //Then you can put the links in an array
});

這是JSON文件格式

{
"links": [
"http://www.clearviewarts.com/thumbnails/Pug.jpg",
"http://www.clearviewarts.com/thumbnails/BabyIndy.jpg",
"and so on.."
]
}

PS始終使用JSON或XML格式進行數據通信。 JSON更好。

如果您無法將圖片文件作為JSON加載,則可以嘗試使用新的換行符將其拆分:

$.get('pics.txt', function(data) {
  $.each(data.split('\n'), function(i, d) {
     $('#gallery').append('<img src="'+d+'"><br>');
  });
});

這會將圖像標簽中的每個圖像URL附加到具有ID庫的DIV中。 您可能想要更改HTML以使其起作用或看起來像您想要的。

注意:這假設您使用的是jQuery

編輯:以最簡單的形式,整個HTML將如下所示。 這就是我測試上面的代碼並得到結果的方式。 假定“ pics.txt”與HTML文件位於同一目錄中。 編輯位置(在$.get('pic/location/pics.txt'等中。使用Google托管的jQuery版本。

<html>
<head></head>
<body>

<div id="gallery"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.get('pix.txt', function(data) {
  $.each(data.split('\n'), function(i, d) {
        $('#gallery').append('<img src="'+d+'"><br>');
  });
});

</script>
</body>    
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM