我试图保存到文件但是收到错误' 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>
我在文件SaveTextAsFile.js中将函数saveTextAsFile()放在与html相同的目录中:
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();
}
答案 0 :(得分:1)
在脚本标记src的开头添加一个斜杠,使其对您的主机绝对,否则,如果您在网址中说"localhost/foo/bar/SaveTextAsFile.js"
,
浏览器会尝试从"localhost/SaveTextAsFile.js"
加载文件,如果您添加斜杠,它会尝试从<script type='text/javascript' src='/SaveTextAsFile.js'></script>
.container-fluid