[英]How to read and display html file
I'm making a html editor but the problem is that when someone needs to view an html file i don't know how to display the text from the file.我正在制作 html 编辑器,但问题是当有人需要查看 html 文件时,我不知道如何显示文件中的文本。
<input type="file" onchange="previewFile()"><br>
<p id="txt1" src="blank.html"></p>
<script>
function previewFile() {
const preview = document.getElementById('txt1');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// reads image file to a blob string
preview.src = window.URL.createObjectURL(file);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
I used this script to read a file and display it by changing the paragraph src to a blob link, but looks like the paragraph dosn't get the text by a html text link using src.我使用此脚本读取文件并通过将段落 src 更改为 blob 链接来显示它,但看起来该段落没有通过使用 src 的 html 文本链接获取文本。 Is there a way to do it?
有没有办法做到这一点?
The paragraph does not have src
attribute, You need to use either innerText
or innerHTML
to display the content.该段落没有
src
属性,您需要使用innerText
或innerHTML
来显示内容。
function previewFile() { const content = document.querySelector('.content'); const [file] = document.querySelector('input[type=file]').files; const reader = new FileReader(); reader.addEventListener("load", () => { // this will then display a text file content.innerText = reader.result; }, false); if (file) { reader.readAsText(file); } }
<input type="file" onchange="previewFile()"><br> <p class="content"></p>
The p tag does not support src attribute so the alternative solutions would be using element.innerHTML= text or you change the p tag into iframe p 标签不支持src属性,因此替代解决方案将使用 element.innerHTML= text 或将 p 标签更改为 iframe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.