简体   繁体   English

简单的jQuery .load示例不起作用

[英]Simple jQuery .load Example Not Working

I'm sure this is a fairly basic question, but I'm relatively new to jQuery so was hoping someone might be able to help. 我确定这是一个相当基本的问题,但是我对jQuery相对较新,所以希望有人能够提供帮助。

Basically, I need to load an HTML snippet into a page. 基本上,我需要将HTML代码段加载到页面中。 This works fine when the snippet contains just HTML, but not when it contains a script. 当代码段仅包含HTML时,而不是脚本时,此方法可以正常工作。

I've stripped down my code to the bare minimum for clarity. 为了清楚起见,我将代码精简到最低限度。 This is index.html: 这是index.html:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>    
</head>
<body>
<h1>Heading</h1>
<div id="banner"></div>
<script>
$(document).ready(function(){
    $('#banner').load('banner.html');
});
</script>

</body>
</html>

And banner.html contains just the following (as an example): banner.html仅包含以下内容(作为示例):

<h2>Subheading</h2>
<script>
document.write('Hello');
</script>

The script is executed, but for some reason it strips out the rest of the HTML in both index.html and banner.html (ie it just displays "Hello" and nothing else). 该脚本已执行,但由于某种原因,它会删除index.html和banner.html中的其余HTML(即,它仅显示“ Hello”,而没有显示其他内容)。

Any help greatly appreciated! 任何帮助,不胜感激!

document.write after the page has load writes to the document, and at the same overwrites everything else currently in the document, that's why you end up with only the string "hello". 页面加载后的document.write写入文档,并同时覆盖文档中当前的所有其他内容,这就是为什么仅以字符串“ hello”结束的原因。

Just remove the document write : 只需删除文件写:

<h2>Subheading</h2>
<p id="test"></p>
<script>
    document.getElementById('test').innerHTML = 'hello';
</script>

that is becuase when banner.html is loaded .. the script inside banner.html get executed, which writes "hello" in your document(the document here is your entire index.html) 这是因为当banner.html被加载时..banner.html中的脚本被执行,该脚本在您的文档中写入“ hello”(此处的文档是您的整个index.html)

one way to understand this is by replacing certain content of banner.html rather than the whole document. 一种理解方法是替换banner.html的某些内容,而不是整个文档。

banner.html banner.html

<h2>Subheading</h2>
<div id="divID"></div>
<script>
  $('#divID').html('hello');  //using jquery .. gets the element with id as divID and replace the HTML 
 </script>

here i am replacing just the div whose id is "divID" rather than replacing the enrite document 在这里,我只替换id为“ divID”的div,而不是替换enrite文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM