我需要显示/附加文件 file.txt 中的数据,其中包含400行,格式如下:
http://www.exemple.com/img1.jpg, title1, subtitle1, description1;
http://www.exemple.com/img2.jpg, title2, subtitle2, description2;
http://www.exemple.com/img3.jpg, title3, subtitle3, description3;
http://www.exemple.com/img4.jpg, title4, subtitle4, description4;
http://www.exemple.com/img5.jpg, title5, subtitle5, description5;
我知道如何将1行附加到<div>
。但是,这里我们每行有4个元素。我需要将它们变成4个可用于显示它们的元素。
我正在使用这个jQuery代码段,对于每行包含1个元素,并且在行尾分割。
$.get('file.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#display').append('<div><img src="' + elem + '"/></div>');
});
});
HTML输出将是:
$('#display').append('<div class="container"><div class="left"><img src="' + src + '"/></div><div class="right">' + title + '<br/>' + subtitle + '<br/>' + description + '</div></div>');
感谢您的见解!
答案 0 :(得分:1)
你可以第二次split
:
$.each(lines, function(n, line) {
// Breaks up each line into ['src', 'title', 'subtitle', 'description']
var elements = line.split(', ');
$('#display').append('<div><img src="' + elements[0] + '"/></div>');
});
答案 1 :(得分:1)
您可以拆分' '
:
$.get('file.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(line, elem) {
var parts = line.split(', '), // this splits the line into pieces
src = parts[0],
title = parts[1],
subtitle = parts[2],
description = parts[3].slice(0, -1); // remove the ';' from the description
// at this point, you have the pieces of your line and can do whatever
// you want with the data
$('#display').append('<div><img src="' + src + '"/></div>');
});
});
答案 2 :(得分:1)
您的错误存在于您拆分的方式......
您需要执行类似的操作,(.when(file)
应替换为.get('file.txt')
:
var file = "http://www.exemple.com/img1.jpg, title1, subtitle1, description1; http://www.exemple.com/img2.jpg, title2, subtitle2, description2; http://www.exemple.com/img3.jpg, title3, subtitle3, description3; http://www.exemple.com/img4.jpg, title4, subtitle4, description4; http://www.exemple.com/img5.jpg, title5, subtitle5, description5;";
function AppendImagesCtrl($) {
$
// .get('file.txt')
.when(file) // this is a fake
.then(file => file.split(/; ?\n? ?/))
.then(lines => lines.map((line, i) => {
line = line.trim();
if(!line) { return ""; }
let [
img, title, subtitle, description
] = line.split(/, ?n? ?/);
return `<article id="${(i + 1)}">
<h1>${title}</h1>
<img src="${img}" alt="${img}" />
</article>`;
}))
.then(view => $('#example').append(view))
;
}
window.jQuery(document).ready(AppendImagesCtrl);
&#13;
img { width: 100px; height: 50px; background: cyan; }
article { padding: 5px 10px; background: lightseagreen; margin-bottom: 5px;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example"></div>
&#13;