gpt4 book ai didi

javascript - 使用javascript逐行读取本地文件

转载 作者:行者123 更新时间:2023-12-03 08:22:31 24 4
gpt4 key购买 nike

我正在努力实现以下任务:

  • 逐行读取文件
  • 在每行中拆分单词
  • 创建动态行,每个单词作为一列。

我尝试了类似下面的方法,但它不起作用:

$.get('test.txt', function(myContentFile) {
var lines = myContentFile.split("\r\n");
var table = document.getElementById("myTableData");

for(var i in lines){
var str = lines[i]
var res = str.split(",");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = res[0];
cell2.innerHTML = res[1];
}

}, 'text');

最佳答案

确保您有 included jQuery before your code executes ,并在文档中添加具有正确 id 值的 table 元素,如下所示:

<table id="myTableData" border="1"><table>

还要确保您的文本文件 (text.txt) 与您的 html 页面位于同一本地文件夹中。

如果满足所有这些条件,您的代码就会运行。尽管如此,仍有一些事情需要调整。查看我添加到您的代码中的更改和注释:

<html>
<head>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<table id="myTableData" border=1><table>

<script type="text/javascript">
$.get('test.txt', function(myContentFile) {
console.log(myContentFile);
// Added: strip ending new-lines from the retrieved text:
myContentFile = myContentFile.replace(/[\r\n]$/, '');
// Modified: split lines also when delimited by linefeeds only:
var lines = myContentFile.split(/\r\n|\n/);
var table = document.getElementById("myTableData");

for(var i in lines){
var str = lines[i]
var res = str.split(",");
// Modified: remove argument to add rows to the end of the table
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = res[0];
// Modified: test that second element exists to prevent "undefined" output
cell2.innerHTML = res[1] ? res[1] : '';
}
}, 'text');
</script>
</body>
</html>

我将以下 test.txt 文件放在同一文件夹中:

This is a test, with something in second column
And a second line, that also has a second column
The third line just has one value

然后,当我在浏览器中打开 html 页面时,我得到以下输出:

| This is a test                    | with something in second column |
| And a second line | that also has a second column |
| The third line just has one value | |

关于javascript - 使用javascript逐行读取本地文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33688261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com