2012-03-15 15 views
0

私は、ページ上の製品をフィルターするナビゲーションを含むページで作業しています。私はjQueryのハッシュチェンジを使用して、リンクがクリックされたとき、およびブラウザの戻るボタンが押されたときにnavリンクに現在の状態を追加したり削除したりしました。フィルタ()関数は、しかし、唯一のナビゲーションリンクがクリックされたとき、私は、ブラウザの戻るボタンをクリックした場合、またはURLが最後にアンカータグが含まれている場合。フィルタ機能を実装したいと思います動作しますここでアンカータグとJqueryフィルター機能を使用したブラウザーの履歴

は、ページへのリンクです:

http://dl.dropbox.com/u/20585252/test/index.htm

そして、ここではreleventでのjQueryのセクションです:

$(document).ready(function(){ 

$(window).hashchange(function(){ 
var hash = location.hash; 

$('#nav a').each(function(){ 
    var that = $(this); 
    that[ that.attr('href') === hash ? 'addClass' : 'removeClass' ]('current'); 
}); 
}) 

$(window).hashchange(); 
filter(); 

}); 


function filter() { 

    $('ul#nav a').click(function() { 


    var filterVal = $(this).attr('rel'); 

    if(filterVal == 'all') { 
     $('ul.product li.hidden').show().removeClass('hidden'); 
    } else { 

     $('ul.product li').hide().each(function() { 
      if(!$(this).hasClass(filterVal)) { 
       $(this).hide().addClass('hidden'); 
      } else { 
       $(this).show().removeClass('hidden'); 
      } 
     }); 
    } 

}); 


} 

右方向へのポイントは、非常に高く評価されるだろう。

答えて

0

うーん、少しトリッキーな私は、コードと少しjiggery-pokeryの穏やかなリファクタリングで、あなたはなhashchangeハンドラからフィルタをトリガすることができるはずだと思います。

以下のコードは、テストされていないとかなり右ではないかもしれないが、先の方法を提供する必要があります:あなたの助けを

$(document).ready(function(){ 
    $(window).hashchange(function(){ 
     var hash = location.hash.replace('#','');//remove # for cross-browser compatibility 
     $('#nav a').each(function(){ 
      var that = $(this); 
      //that[ that.attr('href') === hash ? 'addClass' : 'removeClass' ]('current'); 
      if(that.attr('href') === hash) { 
       that.addClass('current'); 
       filter.call(that);//call filter with '$(this)' as the context 
      } 
      else { 
       that.removeClass('current'); 
      } 
     }); 
    }); 
    function filter() { 
     //Note: 'this' is a jquery object due to the way in which filter is called (in two places). 
     var filterVal = this.attr('rel'); 
     if(filterVal == 'all') { 
      $('ul.product li.hidden').show().removeClass('hidden'); 
     } 
     else { 
      $('ul.product li').hide().each(function() { 
       if(!this.hasClass(filterVal)) { 
        this.hide().addClass('hidden'); 
       } 
       else { 
        this.show().removeClass('hidden'); 
       } 
      }); 
     } 
    } 
    $('ul#nav').on('click', 'a', function(){ 
     filter.call($(this)); 
    }); 
    $(window).hashchange(); 
}); 
+0

おかげで - 私は.replaceように少し微調整するために必要な(「#」、「」 );私はこれは私が後だった正確に何だったことよりも、それはクロスブラウザに優しいが、他にする方法を把握する必要がありますのでなhashchange機能を破りました。その後、あなたはそれがまだ存在しない場合は、 ''#を付加する必要があり、 '#'それを破るを取り外す場合は多くは – user1258303

+0

をapreciated。何かが好きです: 'hash =(location.hash.match(/ ^#/))? location.hash:( '#' + location.hash); ' –

関連する問題