我想让我的代码分开,所以我决定将每个代码分成divhtml 文件。每个 HTML 文件都有一些 jQuery 点击事件。我有 2 个文件index.html和menu.html.
问题是我必须在两个文件中都包含 jQuery 库才能使其工作。
有什么方法可以让我一次包含库并让它在两个文件上都工作?我试图仅将库包含在索引页面中,但是菜单单击不起作用。
我menu.html通过 iframe 包含了文件。
<iframe src="left-menu.html"></iframe>
您可以使用 jQuery方法添加menu.html到 DOM 中。这样创建的 jQuery 实例也适用于从.index.htmlload()index.htmlmenu.html
例如,index.html您可以这样做:
$(document).ready(function() {
$('#some-menu').load('some-local-path/menu.html');
});
请注意,我们如何$('#some-menu')在index.html其中加载menu.html. 还需要注意的是,由于same-origin-policy,作为该load()方法的一部分执行的 AJAX 请求仅适用于相同域、协议和端口中的文件(除非您使用的是CORS)。
在您的 HTML 中:
<body>
<header>
<div data-includeHTML="_HeaderPartial.html"></div>
</header>
<main>
<div>
This is the main content, from the index file
</div>
</main>
<footer>
<div data-includeHTML="_FooterPartial.html"></div>
</footer>
<script>
$(document).ready(function () {
$("div[data-includeHTML]").each(function () {
$(this).load($(this).attr("data-includeHTML"));
});
});
</script>
</body>
在单独的文件“_HeaderPartial.html”中:
<div>
<h1>This is the Header from its _Partial file</h1>
</div>
在单独的文件“_FooterPartial.html”中:
<strong>And this is from the footer partial file</strong>
结果:
这是主要内容,来自索引文件
这是来自页脚部分文件
我有另一个解决方案。它似乎使代码更漂亮更短。首先定义包含函数。
var include = function(beReplacedId,url){
jQuery.get(url,function(data){
jQuery(beReplacedId).replaceWith(data);
});
}
在 html 页面上使用 onload 来触发包含这样的。
<img id="partTopicDetail" onload="include(this,this.id+'.html')" src="img/any-image.png" >
编译器运行完成后,它将替换 img 标签并加载您需要的内容。通过上述技巧,我可以附加到 index.html 中的任何位置