是否可以简化我的AJAX导航代码?

时间:2013-01-22 19:19:32

标签: jquery ajax navigation

我还在学习javascript,我正在建立一个ajax网站,从外部文件(例如test1.php,test2.php)加载每个页面的内容。我花了几个小时拼凑起一些有效的代码,但感觉非常笨重。有关如何简化它的任何建议?或者我正在做的任何事情都是愚蠢的,应该以不同的方式完成?

JS:

$(document).ready(function() {

var hash = window.location.hash.substr(1);

var projectID = $('#topNav a').each(function(){
    var projectID = $(this).attr('id');
    if(hash==projectID){
        var toLoad = hash+'.php .content';
        $('.content').load(toLoad);
        $(this).siblings().removeClass('active');
        $(this).addClass('active');
    }                           
});

$('#topNav a').click(function(){

    var toLoad = $(this).attr('href')+' .content',
        newId = $(this).attr('rel'),        
        oldHeight = $('#shell').css("height"),      
        viewportHeight = $(window).height()

    if (!$(this).hasClass("active")) {

        $(this).siblings().removeClass('active');
        $(this).addClass('active');

        $('<div/>', {
            id: newId,
            class: 'content'
        }).css({ top: viewportHeight + "px", display: "none" }).appendTo('#shell').load(toLoad);

        $('#' + newId).show(function() {
            $(this).animate({ top: "0px", queue: false}, 600);
            $('#shell > div:first').animate({ top: "-" + oldHeight, queue: false}, 600, function() {

                $('#shell > div:first').remove()
            });
        });

        var newHash = $(this).attr('id');
        window.history.pushState(null, "", "#" + newHash);

    }

    return false;
});

window.addEventListener("popstate", function(e) {

    var hash = window.location.hash.substr(1),
        oldHeight = $('#shell').css("height"),      
        viewportHeight = $(window).height()

    var projectID = $('#topNav a').each(function(){
        var projectID = $(this).attr('id');
        if(hash==projectID){
            var toLoad = hash+'.php .content'

            $(this).siblings().removeClass('active');
            $(this).addClass('active');

            $('<div/>', {
                id: hash,
                class: 'content'
            }).css({ top: viewportHeight + "px", display: "none" }).appendTo('#shell').load(toLoad, function() {

                $(this).show(function() {
                    $(this).animate({ top: "0px", queue: false}, 600);
                    $('#shell > div:first').animate({ top: "-" + oldHeight, queue: false}, 600, function() {

                        $('#shell > div:first').remove()
                    });
                });

            });

        }                           
    });

});

});

HTML:

<nav id="topNav">
<a href="test1.php" id="test1" rel="content1" class="active">Test 1</a>
<a href="test2.php" id="test2" rel="content2">Test 2</a>
<a href="test3.php" id="test3"rel="content3">Test 3</a>
</nav>

<div id="shell">

<div id="content1" class="content">

    <p>Here is the first page</p>

</div>

</div>

CSS:

#topNav {
position: fixed; overflow: auto; top: 0; left: 0;
width: 100%; z-index: 100; background: #fff; height: 80px;
}
#topNav a { margin-right: 30px; color: #a9a9a9; }
  #topNav a.active { color: #333; }

#shell { margin: 0px; padding: 0px; width: 100%; height: 100%; }

.content { 
  position: absolute; margin: 0px; padding-bottom: 0px;
  width: 100%; height: 100%;
}
#content1 { background: #000; color: #fff; }
#content2 { background: red; }
#content3 { background: blue; }

1 个答案:

答案 0 :(得分:1)

要点:

  • 很多代码都是重复的 - &gt;识别模式&amp;制作一个插件
  • 您不缓存您的jquery对象
  • 您不使用.on(&amp; delegate event)
  • 你没有链接你的jquery方法

沿着这些线重组(它只是核心和未经测试但应该是一个很好的重启点)

$.fn.extend({

  tofocus : function () {

      var $tofocus=$(this);
      //put your animations/effects/your browser history management stuff
     //addcclass/removeclass 
     //chain everything .end() if necesary (like after .siblings() )
    return $tofocus;


    },      

  loadcontent : function(id) {
       var $t=$(this);
       //look if this content was already loaded 
       //if loaded $("#'+id+'").tofocus() 

      //if not ->
       var viewportHeight=$(window).height();
       var $divcontent = $('<div/>', {
                    "id"   : "content-"+id,
                    "class": 'content'
                     }).css({ 
                      top: viewportHeight + "px", display: "none"       
                 }).appendTo($t).load(id+'.php',function() {
                        $(this).tofocus();
        });
        return $t;
  }
})



$(document).ready(function() {
  //cache your content container 
  // it will  be used every time a nav button is clicked/at init & if using back/fw button -> you'll spare as much access to the dom to create the object
  var $ctt=$("#shell");
  //load first page (id from hashtag on page load ?)
  var hashfirst=...
  $ctt.loadcontent(hashfirst);


  $(document).on("click","#topNav a",function(e) {
            $ctt.loadloadcontent(this.id);
            return false
   })

   window.addEventListener("popstate", function(e) {

            var hash = window.location.hash.substr(1),
            $ctt.loadcontent(hash);

           });
 });