在url中哈希以与ajax进行深层链接

时间:2013-08-19 21:37:06

标签: ajax hash tags deep-linking

我有这段代码用div动画加载div #target中的内容。工作正常,但我不知道如何使用#hash更改链接和网址的实现代码! 我怎么能这样做?

代码:

$(document).ready(function(){
  $("#target").addClass('hide');

  $('.ajaxtrigger').click(function() {   
    var pagina = $(this).attr('href');
    if ($('#target').is(':visible')) {

    }
    $("#target").removeClass('animated show page fadeInRightBig').load(pagina, 
      function() { 
        $("#target").delay(10).transition({ opacity: 1 })
          .addClass('animated show page fadeInRightBig');                        
      }
    );
    return false; 
  });
});

1 个答案:

答案 0 :(得分:0)

尝试使用任何javascript路由器。例如,router.js

像这样修改你的代码(我没有检查这段代码是否有效,但我认为这个想法应该是明确的):

$(document).ready(function(){
  var router = new Router();

  //Define route for your link
  router.route('/loadpath/:href', function(href) { 
    console.log(href);
    if ($('#target').is(':visible')) {
      $("#target").removeClass('animated show page fadeInRightBig').load(href, 
        function() { 
          $("#target").delay(10).transition({ opacity: 1 })
            .addClass('animated show page fadeInRightBig');                        
        }
      );
    }
  });

  router.route('', function(){ console.log("default route")});


  $("#target").addClass('hide');

  // Instead of loading content in click handler, 
  // we just go to the url from href attribute with our custom prefix ('/loadpath/').
  // Router will do rest of job for us. It will trigger an event when url hash is        
  // changes and will call our handler, that will load contents 
  // from appropriate url.
  $('.ajaxtrigger').click(function() {
    router.navigate('/loadpath/' + $(this).attr('href'));   
    return false; 
  });
});