-1

我仍在学习 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; }
4

1 回答 1

1

要点:

  • 很多代码是重复的 -> 识别模式并制作一个插件
  • 你不缓存你的 jquery 对象
  • 你不使用 .on (&delegate 事件)
  • 你不会链接你的 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);

           });
 });
于 2013-01-22T20:47:34.163 回答