Showing content based on a nav link clicked

后端 未结 4 1402
长情又很酷
长情又很酷 2021-01-16 13:09

I have a menu selection that looks like this:

  • About
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 13:29

    A more efficient way would be to add the same class to all links and another class to all content items...

    HTML:

    
    
    
    
    
    

    JavaScript:

    var $content = $('.menu-content');
    
    function showContent(type) {
      // this assumes that you really must select
      // the content using a class and not an ID (which you've 
      // referenced in the href)
      $content.hide().filter('.' + type).show();
    }
    
    $('.menu').on('click', '.menu-btn', function(e) {
      // get the type to pass to showContent by grabbing
      // the hash from the anchor href and removing the first
      // character (the #)
      showContent(e.currentTarget.hash.slice(1));
      e.preventDefault();
    }); 
    
    // show 'about' content only on page load (if you want)
    showContent('about');
    

    Demo on jsbin: http://jsbin.com/hagonesuwo/edit?html,js,output

    ------------------------------------- EDIT -------------------------------------

    I have just seen your edit with a link to your pastebin. If there is only one content item for each nav item then you can use IDs instead...

    HTML:

    
    
    
    
    
    

    JavaScript:

    var $content = $('.menu-content');
    
    function showContent(selector) {
      $content.hide();
      $(selector).show();
    }
    
    $('.menu').on('click', '.menu-btn', function(e) {
      showContent(e.currentTarget.hash);
      e.preventDefault();
    }); 
    
    // show '#about' content only on page load (if you want)
    showContent('#about');
    

    This would be much better as it would mean the navigation would still jump to the relevant content if JS was disabled or failed to download for any reason.

提交回复
热议问题