最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.write() works inline but not using jQuery's .html() - Stack Overflow

programmeradmin2浏览0评论

If I have a document.write already in my dom as the page loads, it writes only where it's called to write. For example:

<div id="d1">
existing text <script>document.write('& doc written text');</script>
</div>
<div>footer</div>

Will render as <div id="d1">existing text & doc written text</div><div>footer</div>

However, if I were to use jQuery to update the html within div, like

$("#d1").html("another approach <script>document.write('wipes out the screen');</script>");

I end up simply with wipes out the screen b/c it essentially gets rid of everything in the document, vs. writing only where the inline script is. How can I .html() with a value containing document.write(), but have it behave the same as if it were in the dom to begin with (see first example). Thanks!

If I have a document.write already in my dom as the page loads, it writes only where it's called to write. For example:

<div id="d1">
existing text <script>document.write('& doc written text');</script>
</div>
<div>footer</div>

Will render as <div id="d1">existing text & doc written text</div><div>footer</div>

However, if I were to use jQuery to update the html within div, like

$("#d1").html("another approach <script>document.write('wipes out the screen');</script>");

I end up simply with wipes out the screen b/c it essentially gets rid of everything in the document, vs. writing only where the inline script is. How can I .html() with a value containing document.write(), but have it behave the same as if it were in the dom to begin with (see first example). Thanks!

Share Improve this question asked Mar 21, 2013 at 18:25 Ian DavisIan Davis 19.5k30 gold badges91 silver badges134 bronze badges 1
  • 1 You can't use document.write() after DOM is loaded, otherwise it will erase your entire document. Is there a reason you want to use it that way? – ulentini Commented Mar 21, 2013 at 18:28
Add a ment  | 

2 Answers 2

Reset to default 4

The html() function replaces the contents of an element. (See the API)

What you want is append().

If the page has fully been written, you can not use document.write(). There is nothing you can do to change how it behaves. You need to rethink what you are doing.

发布评论

评论列表(0)

  1. 暂无评论