Javascript 将文本区域保存为 UTF-8 文件

标签 javascript internet-explorer textarea

我使用以下 Javascript 代码将文本区域保存到用户计算机上的文本文件中。这仅限于我们的内网,并且只允许使用 IE,因此仅限于安全性有限的 IE 并不是一个大问题;但是,我无法使用 php。因此,我想坚持使用 javascript 并调整以下脚本以强制字符集为 UTF-8。我在保存文件时注意到,它可以在记事本和 Notepad++ 中正确读取,但例如在写字板中打开时,很明显 UTF-16 不令人满意。同样,如果我将其保留在保存对话框中并手动将编码更改为 UTF-8,它将保存页面中的所有文本,而不仅仅是文本区域。另外,如果有人知道如何将默认的“保存类型”更改为文本 .txt,那就太好了,但并不重要。

    <script type="text/javascript">
function SaveContentsTXT(element) {     
    if (typeof element == "string")         
        element = document.getElementById(element);
        element3 = document.getElementsByName( 'TXTFILE' )[0];  
    if (element) {         
        if (document.execCommand) {                             
            var oWin = window.open("about:blank", "_blank");
            oWin.document.write((((element.value).replace(/ /g, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).replace(/\n\r?/g, '<br />'));
            oWin.document.close();           
            var success = oWin.document.execCommand('SaveAs', true, element3.value);
            oWin.close();             
            if (!success)                 
                alert("Sorry, your browser does not support this feature or you canceled.");         
            }     
        } 
    } 
</script>

最佳答案

oWin.document.charset="UTF-8";

最终结果:

function SaveContentsTXT(element) {     
    if (typeof element == "string")         
        element = document.getElementById(element);
        txtitle = document.getElementsByName( 'TXTFILE' )[0];  
    if (element) {   
        if (document.execCommand) {                             
            var oWin = window.open("about:blank", "_blank");
            oWin.document.write((((element.value).replace(/ /g, '&nbsp;')).replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')).replace(/\n\r?/g, '<br />'));
            oWin.document.close(); 
            oWin.document.save="text";
            oWin.document.charset="UTF-8";
            var success = oWin.document.execCommand('SaveAs', true, txtitle.value);
            oWin.close();             
            if (!success)                 
                alert("Sorry, your browser does not support this feature or you canceled.");         
            }   
        } 
    } 

关于Javascript 将文本区域保存为 UTF-8 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900140/

相关文章:

javascript - JS 表达式不能作为 ReactJS 中字符串的一部分工作?

css - Wordpress 主题在 IE 中工作起来很奇怪

internet-explorer - IE9 的 IE8 仿真和老实说的 IE8 有什么区别?

java - 将 Libgdx 滚动条添加到 TextArea

php - 在网站上显示问题 30 秒

javascript - 未捕获错误 : Syntax error, 无法识别的表达式:选择器中有双等号 ==

javascript - 每次在 yii2 中使用带有 ajax 刷新的图表

CSS: IE 9 hack for margin-left?\9;没有效果

css - Mobile Safari 在文本区域上不显示滚动条

javascript - html textarea 在 ASP 中设置为 runat ="server"时忽略 javascript