【问题标题】:Javascript anchor navigationJavascript锚导航
【发布时间】:2009-12-21 19:15:17
【问题描述】:

我正在创建一个带有“锚导航”的网站,就像使用 facebook 和 google 邮件一样。我已经让它工作了,但不完全。当我使用#contact 之类的内容加载页面时,除非我单击它的链接,否则它不会加载它。另外,是否有更好、更有效的方法来做我正在做的事情?我不是最擅长 JS 编程的人。

JavaScript

$.navigate = function() {
  // a new link
  if($anchor != document.location.hash){
    // add a preloader
    $("#content")
      .empty()
      .html('<p class="align-center"><img src="assets/images/loading.gif" /></p>');
    // change the anchor saved for next time
    $anchor = document.location.hash;
    // get the variables ready for the get
    var i = $anchor.substring(1).split("/");
    var $page = i[0];
    var $y = (i[1]) ? i[1] : false;
    // get the file
    $.get("callback.php", { x: $page, y: $y }, function(data){
      $("#content")
        .empty()
        .html(data);
    },"html");
  }
};

$(function() {

  var $anchor = "";
  // change from the URI. This dont work.
  if(document.location.hash){ $.navigate(); }

  $("a","#nav")
    .css({backgroundColor:"#f7f7f7"})
    .each(function() { 
      $(this).attr("href","#" + $(this).attr("name")); 
    });  

  setInterval('$.navigate()', 300);

});

HTML:

<div id="nav">  
  <ul class="horizontal-nav">
    <li><a href="http://streetmafia.co.uk/" name="index">Home</a></li>
    <li><a href="http://streetmafia.co.uk/about" name="about">About</a></li>
    <li><a href="http://streetmafia.co.uk/portfolio" name="portfolio">Portfolio</a></li>
    <li><a href="http://streetmafia.co.uk/contact" name="contact">Contact</a></li> 
  </ul>
  <div id="l-nav"></div>
  <div id="r-nav"></div>  
</div>

【问题讨论】:

  • 别忘了接受答案。

标签: javascript jquery ajax fragment-identifier hashchange


【解决方案1】:

试试ReallysimpleHistory jquery 插件。

【讨论】:

    【解决方案2】:

    ReallysimpleHistory 插件也是如此。 我不确定我是否完全理解您的代码,但我会将其分为 2 个函数:

    1. 一个 ajax 加载(包括显示预加载器)
    2. 另一个检查当前哈希(来自 URL)并调用上一个函数

    在您的“$(function() {...”中,您首先调用第二个函数(仅一次)。然后将链接的单击事件与第一个函数绑定。 您可以使用 $(this).attr('name') 在加载函数中获取哈希。

    快速示例(未测试:P):

    function ajaxLoad()
    {
    
     var anchor;
    
     // Check to see if it's being called from an event
     if ( $(this).length > 0 )
     {
       anchor =  $(this).attr('name');  
     }
     else
     {
       anchor = document.location.hash;
     }
    
    }
    

    【讨论】:

      【解决方案3】:

      您可能想查看 jQuery History 项目: http://www.balupton.com/projects/jquery-history

      它比其他的功能更全面,更容易实现,如果很棒的话,它还提供支持。它还有一个功能齐全的 AJAX 扩展,允许您轻松地将 Ajax 请求集成到您的状态/哈希中,从而将您的网站转换为功能齐全的 Web 2.0 应用程序: http://www.balupton.com/projects/jquery-ajaxy

      这是一个使用 jQuery History 的示例(取自演示站点):

      // Bind a handler for ALL hash/state changes
      $.History.bind(function(state){
          // Update the current element to indicate which state we are now on
          $current.text('Our current state is: ['+state+']');
          // Update the page"s title with our current state on the end
          document.title = document_title + ' | ' + state;
      });
      
      // Bind a handler for state: apricots
      $.History.bind('/apricots',function(state){
          // Update Menu
          updateMenu(state);
          // Show apricots tab, hide the other tabs
          $tabs.hide();
          $apricots.stop(true,true).fadeIn(200);
      });
      

      还有一个 jQuery Ajaxy 示例(取自演示站点):

              'page': {
                  selector: '.ajaxy-page',
                  matches: /^\/pages\/?/,
                  request: function(){
                      // Log what is happening
                      window.console.debug('$.Ajaxy.configure.Controllers.page.request', [this,arguments]);
                      // Adjust Menu
                      $menu.children('.active').removeClass('active');
                      // Hide Content
                      $content.stop(true,true).fadeOut(400);
                      // Return true
                      return true;
                  },
                  response: function(){
                      // Prepare
                      var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state;
                      // Log what is happening
                      window.console.debug('$.Ajaxy.configure.Controllers.page.response', [this,arguments], data, state);
                      // Adjust Menu
                      $menu.children(':has(a[href*="'+state+'"])').addClass('active').siblings('.active').removeClass('active');
                      // Show Content
                      var Action = this;
                      $content.html(data.content).fadeIn(400,function(){
                          Action.documentReady($content);
                      });
                      // Return true
                      return true;
      

      如果你想获得查询字符串参数(所以yoursite/page.html#page1?a.b=1&amp;a.c=2),你可以使用:

      $.History.bind(function(state){
          var params = state.queryStringToJSON(); // would give you back {a:{b:1,c:2}}
      }
      

      因此,请查看这些演示链接以了解它们的实际效果以及所有安装和使用详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-15
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-20
        相关资源
        最近更新 更多