且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在xhtml + xml页面中替换document.write()

更新时间:2023-10-27 12:07:58

  var el = document.createElement('div'); 
el.innerHTML ='您用于document.write()'的内容;
document.body.appendChild(el);

请注意,您需要将HTML修正为有效的XHTML,但这应该少得多工作比转换所有代码来使用DOM操作。


I work for a company that writes software which client sites embed with < script language="JavaScript" src=..... etc. etc. We depend quite a bit on document.write to write elements out to the page. One of our clients for some reason has opted to use the content-type "application/xhtml+xml", which makes document.write() unusable in chrome.

I understand why this is, and that DOM-compliant code should create each element, set its attributes, fill it with a text node if needed, attach the text node to its parent and the parent to some page element....

but what's a good workaround that doesn't require all this junk? The write()s therein have so many elements that the resulting code would be hideous if we made nodes and fastened them together like Knex or Legos or what-have-you.

edit: Tried using CDATA, but even this line is condemned similarly by the xhtml parser on the same page as our script embed:

<script language="text/javascript"><![CDATA[document.write('hi');]]></script>

var el = document.createElement('div');
el.innerHTML = 'What you used to document.write()';
document.body.appendChild(el);

Note that you'll need to fix the HTML to be valid XHTML, but that should be much less work than converting all the code to use DOM manipulation.