当前位置: 代码迷 >> JavaScript >> saveTextAsFile未定义
  详细解决方案

saveTextAsFile未定义

热度:42   发布时间:2023-06-07 16:33:22.0

我正在尝试保存到文件,但收到错误'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();
}

在脚本标记src的开头添加斜杠以使其对主机绝对,否则,如果您在URL中说"localhost/foo/bar/" ,浏览器将尝试从"localhost/foo/bar/SaveTextAsFile.js"加载文件"localhost/foo/bar/SaveTextAsFile.js" ,如果添加斜杠,它将尝试从"localhost/SaveTextAsFile.js"加载它

<script type='text/javascript' src='/SaveTextAsFile.js'></script>
  相关解决方案