点击按钮无法调用JavaScript函数实现txt文件内容逐行展示问题
核心问题排查
- 页面未定义id为
inputfile的文件选择控件,无法获取用户上传的txt文件 - 文件读取逻辑中
this.files[0]指向错误:点击事件的this指向按钮元素,不是文件选择控件,无法拿到选中的文件对象 - 换行拆分仅适配Windows系统的
\r\n换行符,Linux/macOS系统下的txt文件会拆分异常 - 逐行输出的终止判断逻辑错误,会漏掉文件最后一行内容
修复后完整代码
<!-- 新增txt文件选择控件 --> <input type="file" id="inputfile" accept=".txt"> <div id="output"></div> <button id="btn">点击展示文件内容</button> <script type="text/javascript"> document.getElementById("btn").addEventListener("click", function () { const input = document.getElementById("inputfile"); if (!input.files.length) { alert("未选择任何文件!"); return; } // 每次点击先清空历史输出 document.getElementById('output').innerHTML = ''; const fr = new FileReader(); fr.onload = function () { if (!fr.result) { return; } // 兼容全系统换行符拆分 const resultAsArray = fr.result.split(/\r?\n/); let index = 0; const displayInterval = setInterval(() => { // 修正终止条件,展示所有行内容 if (index >= resultAsArray.length) { clearInterval(displayInterval); return; } const output = document.getElementById('output'); output.innerHTML += `<div>${resultAsArray[index]}</div>`; index++; }, 1000); } // 修正文件来源,从选择控件获取文件 fr.readAsText(input.files[0]); }); </script>
改动说明
- 补充了专属的txt文件选择控件,限制仅可上传txt格式文件,避免格式不兼容问题
- 修正了文件读取的来源指向,可正常获取用户选中的文件
- 优化了换行符匹配逻辑,适配所有操作系统生成的txt文件
- 调整逐行输出逻辑,不会遗漏文件最后一行内容
- 新增点击清空历史输出的逻辑,避免多次点击内容重复拼接
内容的提问来源于stack exchange,提问作者user16974637
相关产品推荐
相关产品推荐

