我正在尝试保存到文件,但出现错误“saveTextAsFile未定义”,请参见下文
<script type='text/javascript' src='SaveTextAsFile.js'></script>
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
<table>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"></input></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
</table>
我在与HTML相同的目录中的文件SaveTextAsFile.js中具有该函数saveTextAsFile()。
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
最佳答案
在脚本标签src的开头添加斜杠以使其对主机绝对,否则,如果您在url中,请说"localhost/foo/bar/"
,则
浏览器将尝试从"localhost/foo/bar/SaveTextAsFile.js"
加载文件,如果添加斜杠,它将尝试从"localhost/SaveTextAsFile.js"
加载文件
<script type='text/javascript' src='/SaveTextAsFile.js'></script>
关于javascript - saveTextAsFile未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31885936/