jQuery 如何用jQuery选择和替换整个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:47:58  来源:igfitidea点击:

How to select and replace the whole page with jQuery

jqueryjquery-selectorscss-selectors

提问by Felix Andersen

My design of a page forces me to refresh the whole page with html that I have loaded via ajax.

我的页面设计迫使我使用通过 ajax 加载的 html 刷新整个页面。

$('html').replaceWith(data);

$('html').replaceWith(data);

Gives me errors. Any ideas?

给我错误。有任何想法吗?

回答by Robin

I had the same issue, but this didn't help. If you need to also replace the <head>tag (so, the whole page), you can also do

我有同样的问题,但这没有帮助。如果你还需要替​​换<head>标签(所以,整个页面),你也可以这样做

document.write(newPage);

回答by cgp

Use body:

使用身体:

$('body').replaceWith(data);

回答by nilsmagnus

I had some issues with

我有一些问题

$("body").replaceWith(newPage)

giving me some weird css problems, but this worked fine:

给了我一些奇怪的 css 问题,但这很好用:

$("body").html(newPage);

回答by Hamzeen Hameem

this might be the solution you'll require, It replaces the entire document including its head. You won't have any issues loading your new css, js & other resources. I've assumed you receive the new html content by invoking a REST api:

这可能是您需要的解决方案,它会替换整个文档,包括其 head。加载新的 css、js 和其他资源不会有任何问题。我假设您通过调用 REST api 收到新的 html 内容:

$.ajax({
  type: 'POST',
  url: form.attr('action'),
  data: form.serialize(), // serializes form elements
  success: function(response) {
    // re-writes the entire document
    var newDoc = document.open("text/html", "replace");
    newDoc.write(response);
    newDoc.close();
  }
});

回答by Ekrem ?zgür

Strange behavior by jQuery.replaceWith and jQuery.html when executed with 'body' selector. You loose the body tag after the call:

使用“body”选择器执行时 jQuery.replaceWith 和 jQuery.html 的奇怪行为。通话后您松开了 body 标签:

$('body').replaceWith('<body>New body</body>');

It doesn't happen with any other selector as:

任何其他选择器都不会发生这种情况:

$('title').replaceWith('<title>New title</title>');

Also jQuery.html doesn't double the body tag (as it does with other tags), and operates like replaceWith when called like this:

此外,jQuery.html 不会将 body 标签加倍(就像它与其他标签一样),并且在像这样调用时像 replaceWith 一样操作:

$('body').html('<body>New body</body>');

I hope this isn't a grey zone of jQuery. Or if it is, they don't think to fix it. I have applications where I use $('body').html when $('body').replaceWith should be used.

我希望这不是 jQuery 的灰色地带。或者,如果是,他们不认为要修复它。我有一些应用程序在应该使用 $('body').replaceWith 时使用 $('body').html。