您可能想要这样做:
jQuery("body").html("new content");
...其中"new content" 理想情况下只包含通常出现在body 元素中的标记,而不包括其余部分。这将替换 body 元素的内容,同时保留 head 中的任何内容(如样式表信息)。如果您还想更新标题,可以通过document.title = "new title"; 进行更新
编辑我想知道替换 html 元素内的 everything 是否可行,以及会发生什么。所以我这样做了:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
font-weight: bold;
color: blue;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
(function() {
$(document).ready(pageInit);
function pageInit() {
$('#btnChange').live('click', changePage);
$('#btnHiThere').live('click', sayHi);
}
function changePage() {
$('html').html(
"<head><\/head>" +
"<body>" +
"<input type='button' id='btnHiThere' value='Click for Alert'>" +
"<p>Note how this text now looks.<\/p>" +
"<\/body>"
);
}
function sayHi() {
alert("Hi there");
}
})();
</script>
</head>
<body>
<input type='button' id='btnHiThere' value='Click for Alert'>
<input type='button' id='btnChange' value='Change Page'>
<p>Note now this text current appears in a sans-serif, bold, blue font.</p>
</body>
</html>
结果非常有趣——我最终得到了一个没有 head 或 body 的 DOM 结构,只有 html 和 @987654331 的后代@ 和 body 在里面。这可能是搞乱新内容中(新)样式的原因。我直接得到了基本相同的结果设置innerHTML(这可能是它在jQuery中不起作用的原因;jQuery在可以的时候使用innerHTML,尽管它在不能时不这样做非常复杂);而如果我通过document.createElement 和document.appendChild 显式创建head 和body 元素来做类似的事情,它会起作用。
几乎可以肯定,所有这些都意味着付出的努力多于其价值。
但是:请注意,更改 head 和 body 元素的 content 似乎可以正常工作:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test Page</title>
<style type='text/css'>
body {
font-family: sans-serif;
font-weight: bold;
color: blue;
}
</style>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>
<script type='text/javascript'>
(function() {
$(document).ready(pageInit);
function pageInit() {
$('#btnChange').live('click', changePage);
$('#btnHiThere').live('click', sayHi);
}
function changePage() {
$('head').html(
"<style type='text/css'>\n" +
"body { color: green; }\n" +
"<\/style>\n"
);
$('body').html(
"<input type='button' id='btnHiThere' value='Click for Alert'>" +
"<p>Note how this text now looks.<\/p>"
);
}
function sayHi() {
alert("Hi there");
}
})();
</script>
</head>
<body>
<input type='button' id='btnHiThere' value='Click for Alert'>
<input type='button' id='btnChange' value='Change Page'>
<p>Note now this text current appears in a sans-serif, bold, blue font.</p>
</body>
</html>
因此,如果您将要加载的“页面”分为头部和身体部分,您可以轻松地对其进行更新。