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

Simple jQuery .load Example Not Working

本文关键字:不起作用 load jQuery 简单      更新时间:2023-09-26

我相信这是一个相当基本的问题,但我对jQuery相对陌生,所以希望有人能帮忙。

基本上,我需要将一个HTML片段加载到一个页面中。当代码段只包含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>

banner.html只包含以下内容(例如):

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

脚本被执行,但由于某种原因,它去掉了index.HTML和banner.HTML中的其余HTML(即,它只显示"Hello",而不显示其他内容)。

非常感谢您的帮助!

document.write在页面加载后写入文档,同时覆盖文档中当前的所有其他内容,这就是为什么最终只得到字符串"hello"的原因。

只需删除文档即可写入:

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

这是加载banner.html时的becuase。。banner.html中的脚本被执行,它在您的文档中写"hello"(这里的文档是您的整个index.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>

这里我只替换id为"divID"的div,而不是替换enrite文档