What are alternatives to [removed]?

2018-12-31 09:31发布

In tutorials I've learnt to use document.write. Now I understand that by many this is frowned upon. I've tried print(), but then it literally sends it to the printer.

So what are alternatives I should use, and why shouldn't I use document.write? Both w3schools and MDN use document.write.

10条回答
美炸的是我
2楼-- · 2018-12-31 09:48

This is probably the most correct, direct replacement: insertAdjacentHTML.

查看更多
只靠听说
3楼-- · 2018-12-31 09:52

As a recommended alternative to document.write you could use DOM manipulation to directly query and add node elements to the DOM.

查看更多
唯独是你
4楼-- · 2018-12-31 09:55
像晚风撩人
5楼-- · 2018-12-31 09:58

Just dropping a note here to say that, although using document.write is highly frowned upon due to performance concerns (synchronous DOM injection and evaluation), there is also no actual 1:1 alternative if you are using document.write to inject script tags on demand.

There are a lot of great ways to avoid having to do this (e.g. script loaders like RequireJS that manage your dependency chains) but they are more invasive and so are best used throughout the site/application.

查看更多
怪性笑人.
6楼-- · 2018-12-31 10:01

I'm not sure if this will work exactly, but I thought of

var docwrite = function(doc) {               
    document.write(doc);          
};

This solved the problem with the error messages for me.

查看更多
忆尘夕之涩
7楼-- · 2018-12-31 10:04

The question depends on what you are actually trying to do.

Usually, instead of doing document.write you can use someElement.innerHTML or better, document.createElement with an someElement.appendChild.

You can also consider using a library like jQuery and using the modification functions in there: http://api.jquery.com/category/manipulation/

查看更多
登录 后发表回答