就地替换整个 HTML 文档
我试图避免使用数据 URI,因为我不希望生成的文档存储在浏览器的历史记录中。是否可以就地替换整个 HTML 文档?
我尝试了 jQuery("html").html("....")
,但是 style
信息无法保留。
I'm trying to avoid using a data URI because I do not want the generated document to be stored in the browser's history. Is it possible to replace the entire HTML document in-place?
I tried jQuery("html").html("<html>....</html>")
, but the style
information does not survive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想要这样做:
...其中
"new content"
理想情况下仅包含通常出现在body
元素中的标记,而不包含其余部分。这将替换 body 元素的内容,同时保留head
中的任何内容(例如样式表信息)。如果您还想更新标题,可以通过document.title = "new title";
编辑 我想知道如何替换所有内容 在
html
元素内,是否有效,以及会发生什么。所以我这样做了:结果非常有趣——我最终得到了一个根本没有
head
或body
的 DOM 结构,只是html
,其中包含head
和body
的后代。这可能就是新内容中(新)样式混乱的原因。我直接得到本质上相同的结果设置innerHTML
(这可能就是它在 jQuery 中不起作用的原因;jQuery 在可以的时候使用innerHTML
,尽管它非常复杂,不这样做所以当它不能时);而如果我通过document.createElement
和document.appendChild
显式创建head
和body
元素来执行类似的操作, 有用。所有这些几乎肯定意味着这比它的价值更多的努力。
但是:请注意,更改
head
和body 的内容
元素似乎工作得很好:因此,如果您将要加载的“页面”分离到头部和正文部分,您可以轻松地就地更新它。
You probably want to do this:
...where
"new content"
would ideally only include the markup that would normally appear within thebody
element and not the rest. That will replace the body element's contents, whilst leaving anything you have inhead
(like style sheet information) alone. If you also want to update the title, you can do that viadocument.title = "new title";
Edit I got to wondering about replacing everything inside the
html
element, whether that would work, and what would happen. So I did this:And the results were quite interesting — I end up with a DOM structure that doesn't have a
head
orbody
at all, justhtml
with the descendants ofhead
andbody
inside. This is probably what's messing up the (new) styling in the new content. I get essentially the same result settinginnerHTML
directly (which may be why it doesn't work in jQuery; jQuery usesinnerHTML
when it can, although it's very sophisticated about not doing so when it can't); whereas if I do something similar by explicitly creating thehead
andbody
elements viadocument.createElement
anddocument.appendChild
, it works.All of which almost certainly means this is more effort than it's worth.
But: Note that changing the content of the
head
andbody
elements seems to work just fine:So if you separate the "page" you're loading into head and body parts, you can easily update it in place.
没有jquery:
No jquery: