我在 header.html
中有这段代码:
<nav role="navigation">
<ul class="nav">
<li><a id="home" href="index.html" class="current">home</a></li>
<li><a id="about" href="includes/test.html">about</a></li>
<li><a id="resources" href="#">resources</a></li>
<li><a id="archive" href="#">archives</a></li>
</ul>
</nav>
现在,一切似乎都很好,直到我的 index.html
从另一个文件夹加载文件以使用 id="header"
, id="content"填充 div "
和 id="footer"
使用:
$(function() {
$("#mainhead").load("templates/header.html");
$("#content").load("templates/content.html");
$("#footer").load("templates/footer.html");
});
我的问题是 - 如何将 div id="content"
中的内容替换为可通过单击导航菜单中的链接访问的另一个 HTML 页面中的内容?
最佳答案
将加载导航的代码更改为此...
$("#mainhead").load("templates/header.html", function() {
$(this).find(".nav a").on("click", function(e) {
e.preventDefault(); // stop the link from firing as normal
$("#content").load(this.href); // load the file specified by the link
});
});
这将在标题导航中的链接“ajaxify”加载后,以便为每个链接加载内容 div,而无需离开页面导航。只需确保每个 header 链接都具有正确的 href
值即可加载您要加载的内容。
关于javascript - 使用 jQuery 替换 div 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32479373/