JQuery:用外部文件中的html替换DIV内容。完整的例子? [英] JQuery: replace DIV contents with html from an external file. Full example?
问题描述
问题
在页面上启用jQuery然后使用它来用HTML文本替换DIV内容的完整代码是什么来自外部文件?
What's the full code to enable jQuery on a page and then use it to replace the contents of a DIV with HTML text from an external file?
背景
我是jQuery的新手我渴望与它合作,所以我可以学习它。我有一个网站,我需要替换每个页面上存在的相同div(页脚)的内容。幸运的是,每个页面都已导入相同的头文件。所以我要用一些jQuery魔法来修改那个头文件!我无法找到 完整示例 ,我认为其他人可能会遇到类似的问题。谁比SO大师更好问?
I'm brand new to jQuery and I'm eager to work with it so I can learn it. I have a site where I need to replace the contents of the same div (a footer) that exists on every page. Fortunately, each of these pages already imports the same header file. So I'm going to modify that header file with some jQuery magic! I'm having trouble finding full examples and I figured other's might have similar questions. Who better to ask than the SO gurus?
示例
给出一个基本的HTML文件 Example.html
:
Given a basic HTML file Example.html
:
<html>
<head>
</head>
<body>
<div id="selectedTarget">
Existing content.
</div>
</body>
</html>
外部文件包含/ contentSnippet.html
包含一段html:
And an external file includes/contentSnippet.html
containing a snippet of html:
<p>
Hello World!
</p>
新的 Example.html
文件是什么?那将链接正确的jQuery库(来自./js目录)并通过jQuery替换div的内容?
What would the new Example.html
file be that would link the proper jQuery libraries (from the ./js directory) and replace the div's contents via jQuery?
推荐答案
确定,我会咬... ...
ok, I'll bite...
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#selectedTarget').load('includes/contentSnippet.html');
});
</script>
</head>
<body>
<div id="selectedTarget">
Existing content.
</div>
</body>
</html>
注:
- I've linked the jquery libraries directly from jQuery's public CDN (which is allowed and encouraged)
- You can find the documentation for jQuery's
load()
function right here.
这篇关于JQuery:用外部文件中的html替换DIV内容。完整的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!