简体   繁体   中英

Browsers bug on document.write

I have multiple widgets like this

var c2409 = "<div class="products">PRODUCT1 PRODUCT2 PRODUCT4 ...</div>";
document.write(c2409)

And I call this

<script src="website/getjswidget.aspx?cid=xxxx-xxxx-xxx-xxxx"></script>

Now looks like sometime after I clear the cache, this replace everything in my html and I get a blank page only with this div from my widget. Any other solutions to replace document.write?

This is by design.

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

Source

If you want to append data to your webpage, use this:

document.body.innerHTML += 'your HTML code to add'

Edit: If you want to show this in a particular element, you can do something like this:

<!-- HTML element -->
<div id="myData"></div>

<!- Javascript code -->
document.getElementById('myData').innerHTML += 'your HTML'

Edit 2 (After some searching): You can get the current script element by using document.currentScript and then perhaps use Node.insertBefore to create a div right before that script tag, to put your data in.

Edit 3: Apparently document.currentScript doesn't work in IE. But this answer may help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM