document.write() 的跨浏览器支持

Cross browser support for document.write()

我有一个 HTML 文档对象分配给变量 var doc。使用此文档对象,我将字符串值呈现到文本文件中,其中值正在呈现和写入,但在 IE11 浏览器中格式不正确但在 IE8、IE10、ff n chrome.Please 中工作正常 chrome.Please 找到我的以下代码:

  function savecontent(str){
  var filename = "data.txt";
  var str=replaceAll(str,'<doublequote>','"');
  var w = window.frames.w;
  if( !w )
     {
             w = document.createElement( 'iframe' );
             w.id = 'w';
             w.style.display = 'none';
             document.body.insertBefore( w,null );
             w = window.frames.w;
             if( !w )
             {
                     w = window.open( '', '_temp', 'width=100,height=100' );
                     if( !w )
                     {
                             window.alert( 'Sorry, could not create file.' ); return false;
                     }
             }
     }

  var doc = w.document;
  doc.open('text/plain');
  doc.charset="iso-8859-1";
  doc.write(str);
  doc.close(doc.write(str));
  w.close();
  if( doc.execCommand( 'SaveAs', false, filename ) )
     {
             window.alert("Please save the file.");
     }
}

我的 str 可能是这样的 employee_firstname,employee_lastname,employee_id,employee_salary,员工账号,employee_dob等..

在 IE11 中呈现为,

employee_firstname,employee_lastname,
employee_id,employee_salary,employee accountno,employee_dob

但正如预期的那样,数据在 IE8 中呈现,ff n chrome 格式如下:

employee_firstname,employee_lastname,employee_id,
employee_salary,employee accountno,employee_dob

我在其他浏览器如 IE8 中注意到的不同,FF n chrome 是换行符 与其他浏览器相比,IE11 中的情况有所不同。 谁能告诉我如何在 IE11 浏览器或任何替代 document.write() 的文本文件中正确格式化数据呈现?

问题无法完全从提供的代码中重建出来,但问题的核心似乎是您正在生成一个要在内联框架中显示的新文档,使用 open() 方法Document 对象。这是相对较好的支持,但前提是创建的文档是 HTML 文档,而不是纯文本文档。

当您尝试使用 text/plain 格式时,浏览器的处理方式不同。他们实际上创建了一个 HTML 文档,放置在创建文档的 DOM 树中。它包含一个 body 部分,该部分要么只包含您编写的文本,要么包含一个 pre 元素包装器,使其按原样显示。例如,旧版本的 IE 会生成 pre 元素,而 IE 11 不会。有人可能会争辩说 IE 11 做了正确的事情:作为纯文本并不意味着文本应该按照分割成行的原样呈现。

无论如何,避免这种情况的方法是生成一个 HTML 文档并在您的代码中插入 pre 包装器,前提是您希望按原样显示文本:

doc.open('text/html');
doc.write('<pre>' + str + '</pre>');