[我正在使用JQuery加载网站的导航栏和正文,并且我想更改正文内容,请单击导航栏中的某些按钮。我可以使用JavaScript来做到这一点吗?我该怎么办?
[我一直在寻找解决方案,但没有发现任何问题。在此先感谢
html
<header>
<script>
$(function () {
$("header").load("./dist/includes/navbar.html");
});
</script>
</header>
<!-- END of Section NavBar -->
<main>
<script>
$(function () {
$("main").load("./dist/includes/home.html");
});
</script>
</main>
<!-- Section Footer -->
<footer class="footer">
<script>
$(function () {
$("footer").load("./dist/includes/footer.html");
});
</script>
</footer>
当我单击带有id =“ nav-link”的按钮时,我想更改home.html加载的文件
这里是屏幕截图
请考虑以下代码。
$(function() {
// Load content
$("header").load("./dist/includes/navbar.html");
$("main").load("./dist/includes/home.html");
$("footer").load("./dist/includes/footer.html");
// Prpgram Events
$("header").on("click", "button", function(ev) {
console.log("Nav Button was clicked");
$("main p").append("<a href='#'>New Page</a>");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Section NavBar -->
<header></header>
<!-- END of Section NavBar -->
<main></main>
<!-- Section Footer -->
<footer class="footer"></footer>
<!-- END of Section Footer -->
使用jQuery,我们加载内容。由于ready
上的DOM中不存在该内容,因此我们将使用.on()
将事件回调委托给现在已加载的项目。
因此,例如,以下HTML添加到了标题中:
<button>Show Link</button>
单击此按钮将执行匿名回调并将链接附加到main中。