首页 > 解决方案 > 单击侧边栏时如何更改内容

问题描述

我在这段代码中有侧边栏:

     <nav id="sidebar">


        <ul class="list-unstyled components">


            <li >
                <a href="#">Home</a>
            </li>

            <li>
                <a href="#">Page1</a>
            </li>

        </ul>


    </nav>

现在我想更改用户单击侧边栏按钮(主页或 Page1)时的唯一内容

我已经有这两个内容的正文(主页和第 1 页)

标签: javascripthtmlcss

解决方案


尝试使用此代码。我在评论中写了解释

//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>


推荐阅读