你可能想要这样做:
jQuery("body").html("new content");
... where"new content"
理想情况下只包括通常出现在body
元素中的标记,而不包括其余部分。这将替换 body 元素的内容,同时保留您拥有的任何内容head
(如样式表信息)。如果您还想更新标题,可以通过document.title = "new title";
编辑我想知道替换元素内的所有html
内容,这是否可行,以及会发生什么。所以我这样做了:
<!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>
结果非常有趣——我最终得到了一个没有 a head
orbody
的DOM 结构,只有和html
的后代。这可能是搞乱新内容中(新)样式的原因。我直接得到了基本相同的结果设置(这可能是它在 jQuery 中不起作用的原因;jQuery在可以时使用,尽管它在不能时不这样做非常复杂);而如果我通过and显式创建and元素来做类似的事情,它就可以工作。head
body
innerHTML
innerHTML
head
body
document.createElement
document.appendChild
所有这些几乎可以肯定地意味着这比它值得付出的努力更多。
但是:请注意,更改and元素的内容似乎可以正常工作:head
body
<!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>
因此,如果您将要加载的“页面”分为头部和身体部分,您可以轻松地对其进行更新。