javascript - 单击侧边栏时如何更改内容
问题描述
我在这段代码中有侧边栏:
<nav id="sidebar">
<ul class="list-unstyled components">
<li >
<a href="#">Home</a>
</li>
<li>
<a href="#">Page1</a>
</li>
</ul>
</nav>
现在我想更改用户单击侧边栏按钮(主页或 Page1)时的唯一内容
我已经有这两个内容的正文(主页和第 1 页)
解决方案
尝试使用此代码。我在评论中写了解释
//container is the selected element into which the content is to be loaded
var container = document.querySelector('#content'),
//these are the selectors for your links
linkHome = document.querySelector('#link__home'),
linkPage1 = document.querySelector('#link__page1');
//function that loads content
function loadContent(content) {
// AJAX request
var xhr = new XMLHttpRequest();
xhr.open('POST', content, true);
xhr.onload = function() {
var el = document.createElement('div');
el.innerHTML = this.response;
container.empty()
container.prepend(el);
}
xhr.send();
}
//After clicking the selector it will start the function loading the content. Enter the URL to your files in the appropriate place
linkHome.addEventListener('click', function(e){
loadContent('/URL/TO/home.html');
e.preventDefault() ;
});
linkPage1.addEventListener('click', function(e){
loadContent('/URL/TO/page1.html');
e.preventDefault() ;
});
<nav id="sidebar">
<ul class="list-unstyled components">
<li>
<!-- Add to your links ID attribure -->
<a id="link__home" href="#">Home</a>
</li>
<li>
<!-- Add to your links ID attribure -->
<a id="link__page1" href="#">Page1</a>
</li>
</ul>
</nav>
<div id="content"></div>
推荐阅读
- python - 在字典列表中查找重复值并总结其他相关值
- python - 如何在使用 base64 编码图像的同时使用 tensorflow 部署 keras 模型?
- powershell - PowerShell 是否会产生创建以数字命名的文件的副作用?
- javascript - 使用 async.apply 时如何保持 this 的值?
- html - 将 html 页面或 jsp 页面链接到多个 django 应用程序
- python - 访问主机上的课程
- c# - 如何在 msbuild 中读取 environmentVariables ?asp.net 核心 c#
- multithreading - Flask 与 PyQt5 - Flask 控制程序流程?
- django - 如何为身份验证创建自定义 django 验证
- python - Prometheus pushgateway 简单的指标监视器