使用jQuery显示文本文件中的数据 [英] Display data from text file with jQuery

查看:85
本文介绍了使用jQuery显示文本文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示/添加文件 file.txt 中的数据,该文件包含400行,格式如下:

I need to display/append the data from a file, file.txt, containing 400 lines which are in the following format:

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个可以用来显示它们的元素.

I know how to append 1 line into a <div>. But, here we have 4 elements on each line. I need to turn them into 4 elements that I could use to display them.

我正在使用这个jQuery代码段,该代码段对于每行包含1个元素的行都可以正常工作,并在行尾进行拆分.

I am using this jQuery snippet that works fine for each line with 1 element and splits at the end of the line.

$.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>');

感谢您的见解!

推荐答案

您的错误在于您拆分的方式...

Your error resides on the way you split...

您需要执行类似的操作,(.when(file)应该替换为.get('file.txt'):

You need to do something like that, (.when(file) should be replaced with .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);

img { width: 100px; height: 50px; background: cyan; }
article { padding: 5px 10px; background: lightseagreen; margin-bottom: 5px;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example"></div>

这篇关于使用jQuery显示文本文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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