2012-03-15 84 views
0

我正在頁面上使用導航過濾頁面上的產品。我已經使用jQuery hashchange在點擊鏈接和按下瀏覽器後退按鈕時嚮導航鏈接添加和刪除當前狀態。然而,filter()函數只在導航鏈接被點擊時才起作用,我想在點擊瀏覽器後退按鈕或者在結尾處包含錨點標記時實現過濾器功能。帶JQuery過濾器函數的錨標記和瀏覽器歷史記錄

這裏的鏈接頁面:

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

下面是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 2012-03-15 11:04:42

+0

如果刪除'#'將其分開,那麼如果它不存在,則需要預先加上'#'。例如:'hash =(location.hash.match(/ ^#/))? location.hash:('#'+ location.hash);' – 2012-03-15 12:35:59