jQuery 将 html 加载到 div 而不更改页面的其余部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17371888/
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
Load html into div without changing the rest of page
提问by cruxi
So I've seen tons of people asking how to load html into a div, and my code does that fine....but then the rest of the page changes when I load the html into the div.
所以我看到很多人问如何将 html 加载到 div 中,我的代码做得很好......但是当我将 html 加载到 div 时,页面的其余部分会发生变化。
I have a page a.html that looks like this, and loads b.html
我有一个看起来像这样的页面 a.html,并加载了 b.html
a.html
一个.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$("#includedContent").load("b.html");
});
</script>
<div id="includedContent"></div>
<h1>This is why I rule</h1>
</head>
</html>
then b.html looks like this
然后 b.html 看起来像这样
<p> This is my include file </p>
<p> This is my include file </p>
What happens is a.html loads and I can see This is why I rule
momentarily, but then the code goes out and gets b.html. When b.html loads I can ONLY see This is my include file
and the 'This is why I rule' message disappears...
会发生什么是 a.html 加载,我可以This is why I rule
暂时看到,但随后代码消失并获取 b.html。当 b.html 加载时,我只能看到This is my include file
并且“这就是我统治的原因”消息消失了......
Why is this? How do I prevent it? It does this on all browsers I have tested it on.
为什么是这样?我该如何预防?它在我测试过的所有浏览器上都这样做。
回答by cruxi
You have to write your html code into a <body> </body>
你必须把你的 html 代码写成 <body> </body>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
<h1>This is why I rule</h1>
</body>
</html>
回答by Yotam Omer
All your HTML markup is in the head
section not the body
您所有的 HTML 标记都在该head
部分而不是body
try this:
尝试这个:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
<h1>This is why I rule</h1>
</body>
</html>