有多种方法可以实现这种包含,以使代码更易于维护。
PHP
当然,如果你想使用 PHP,首先想到的是使用include() http://www.php.net/manual/en/function.include.php它包含并评估外部文件或脚本中的代码。
您可以这样使用它:
<?php include('path/to/file.html'); ?>
Note!请注意:您的容器文件必须是.php
文件以便从服务器评估该指令。您只需更改文件扩展名即可实现此目的。当然,还要确保您的服务器可以解析 PHP。
另外,请注意与include_once() http://php.net/manual/en/function.include-once.php,在这种情况下我不会推荐。
SSI(包括服务器端)
If you don't want to use PHP, you can do that very simple and clean with a Server side include http://httpd.apache.org/docs/1.3/howto/ssi.html[Wikipedia http://en.wikipedia.org/wiki/Server_Side_Includes]. An SSI looks like an HTML comment:
<!--#include virtual="your.html" -->
Note!你必须确保有mod_include http://httpd.apache.org/docs/1.3/mod/mod_include.html在您的 Apache 服务器中安装并启用,并在您的httpd.conf
or .htaccess
file:
Options +Includes
阅读上面的文档链接以获取更多信息。
客户端包括
您的问题实际上指定在 JS 或 jQuery 中执行此操作。不确定它是否是因为您不知道服务器端选项,或者您是否真的想要客户端选项。无论如何,还有一些客户端解决方案。
考虑到这种可能性,我会推荐服务器端解决您的问题。
IFrame元素
The <iframe> https://developer.mozilla.org/en-US/docs/HTML/Element/iframe元素包含页面中单独区域中外部文件的内容。你可以像这样使用它:
<iframe src="your.html" width="x" height="y"><p>Fallback text</p></iframe>
对象元素
The <object> https://developer.mozilla.org/en-US/docs/HTML/Element/object元素做了类似的事情<iframe>
,但虽然后者更多地被设计为一种手段sandbox一个应用程序,前者感觉更集成在您的页面中。用法如下:
<object type="text/html" data="your.html"></object>
JavaScript 插入
将代码转换为 Javascript 文件并指示该文件将内容插入到 DOM 中。这是一个例子
外部.js
var element = '<div>
<ul>
<li class="current"><a href=".html" ></a></li>
<li><a href=".html"></a></li>
<li><a href=".html"></a></li>
<li><a href=".html"></a></li>
</ul>
</div>';
容器.html
<script type="text/javascript" src="external.js"></script>
<script>
document.getElementById('#containing-element').innerHTML(element);
</script>
AJAX
jQuery 可以帮助您轻松处理一些 AJAX 调用。你可以使用jQuery.get() http://api.jquery.com/jQuery.get/ or jQuery.load() http://api.jquery.com/load/。我建议你使用后者,因为load()
将加载的元素直接注入到 DOM 中,并且您还可以准确指定要加载的部分,这非常有用,特别是如果您想将所有包含内容存储在一个外部 HTML 文件中。
jQuery(document).ready(function ($){
$('#containing-element').load('your.html');
});