在JavaScript中,我一直在尝试创建一个函数,将段落元素的innerHTML设置为本地.txt文件的内容。所以我想将文件中的文本提取到网页上的一个段落中。
我做了一些研究,但没有一种技术有效。
我根据您的要求创建了一个 JavaScript 示例。尝试一下:
function readTextFile() {
var fileAttach = document.getElementById('fileAttach');
if (fileAttach.files.length > 0) {
var file = fileAttach.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var fileTxt = e.target.result;
var container = document.getElementById('fileTxt');
var lines = fileTxt.split('\n');
lines.forEach(function (line) {
if (line.trim() !== '') {
var paragraph = document.createElement('p');
paragraph.textContent = line;
container.appendChild(paragraph);
}
});
};
reader.readAsText(file);
} else {
alert('Please select a file.');
}
}
document.getElementById('fileAttach').addEventListener('change', readTextFile);
<input type="file" id="fileAttach" />
<div id="fileTxt"></div>