我正在尝试创建一个小书签,它允许教师突出显示网页上的文本并将该选择下载为纯文本 (.txt) 文件。我有a demo page设置为显示我正在做的事情以及我陷入困境的地方。
在演示页面上,我可以突出显示文本并使用“下载选择”按钮直接下载它。但是,如果您错误突出显示,则必须返回并重做。 “制作页面”按钮抓取突出显示的文本并创建一个包含文本的弹出窗口以进行校对。
script.js
function makePage(text) {
var text = "";
if(typeof window.getSelection != "undefined") {
text = window.getSelection().toString();
var newPage = window.open("", null, "height=200,width=300,status=yes,menubar=no");
newPage.document.write("<body><a id='download' download='text.txt'></a><p id='copy'>" + text + "</p><button id='download' onclick='getPlainText()'>Download</button><scipt type='text/javascript' src='script.js' defer></script></body></html>");
console.log(text)
}
}
function getPlainText(copy) {
var text = "";
if(typeof window.getSelection != "undefined") {
text = window.getElementById('copy').innerContent;
var download = document.getElementById('download');
download.href = 'data:text/plain;charset:utf-8,' + encodeURIComponent(text);
var event = new MouseEvent('click');
download.dispatchEvent(event);
}
return text;
}
当我单击弹出窗口上的“下载”按钮时,我在控制台中收到 TypeError:
未捕获类型错误:window.getElementById 不是函数
我已经移动了文档中的脚本,但无论它在哪里,错误都会返回,而且我不明白为什么。关于如何让它发挥作用有什么想法吗?
最佳答案
正确的语法是
document.getElementById()
尝试
function getPlainText(copy) {
var text = "";
if(typeof window.getSelection != "undefined") {
text = document.getElementById('copy').innerContent;
var download = document.getElementById('download');
download.href = 'data:text/plain;charset:utf-8,' + encodeURIComponent(text);
var event = new MouseEvent('click');
download.dispatchEvent(event);
}
return text;
}
关于javascript - 从动态创建的窗口下载文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33169914/