2012-02-18 40 views
0

我正在使用ajaxify.js插件https://github.com/browserstate/ajaxify動態加載內容。jQuery + Javascript:合併document.ready和ajax之間的重複函數加載

我有一些click功能,我綁定在文檔就緒,但必須另外把這些功能在我的ajax加載函數內重新綁定點擊事件到新添加的內容。我以前曾嘗試過使用一組live函數,但它們不起作用。

無論如何,我有兩次下面的代碼,一次在document.ready(function(){ })裏面,並且在加載內容之後再次加入ajaxify.js。

我知道這是多餘的,但我不確定如何去寫函數,因爲我可以在其他地方「包括」它們。我怎樣才能優化這些功能,以便我可以合併它們並以有效的方式再次使用它們?

謝謝!

 var $filterclear = $('.filters .filter-clear'), 
      filtercount = $filterclear.length, 
      $searchedfor = $('.searched-for'), 
      is_search = $searchedfor.length; 

     $filterclear.bind('click', function(){ 
      var $me = $(this); 

      if(filtercount == 3) { 
       $('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast'); 
       $(this).addClass('filter-out').fadeOut('fast'); 
      } else { 
       $(this).addClass('filter-out').fadeOut('fast'); 
      } 

      if($me.hasClass('clear-all') || filtercount == 1) { 
       $filterclear.addClass('filter-out').fadeOut('fast'); 
       if(is_search !== 0) { 
        $('.filters').fadeOut(); 
       } 
      } 
     });  

     $('.tag.remove-term').bind('click', function(){ 
      var $me = $(this), 
       mytext = $me.text(), 
       $myfilter = $('.filters .filter-clear:contains("'+ mytext +'")'); 

      if(filtercount == 3) { 
       $('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast'); 
       $myfilter.addClass('filter-out').fadeOut('fast'); 
      } else { 
       $myfilter.addClass('filter-out').fadeOut('fast'); 
      } 
     }); 

     $searchedfor.find('.filter-clear').bind('click',function(){ 
      $searchedfor.fadeOut(); 
     }); 
+0

使用'live'事件肯定聽起來像是應付動態頁面的最佳方式。 「live」有什麼問題? – 2012-02-18 23:07:24

+0

它只是不工作! – 2012-02-19 00:43:08

回答

1

定義一個新的功能應該工作(我沒有測試):

var $filterclear = $('.filters .filter-clear'), 
    filtercount = $filterclear.length, 
    $searchedfor = $('.searched-for'), 
    is_search = $searchedfor.length; 

var doSomething($myfilter) { 
    if(filtercount == 3) { 
     $('.clear-all.filter-clear').addClass('filter-out').fadeOut('fast'); 
    } 
    $myfilter.addClass('filter-out').fadeOut('fast'); 
}; 

$filterclear.bind('click', function() { 
    var $me = $(this); 

    doSomething($me); 

    if($me.hasClass('clear-all') || filtercount == 1) { 
     $filterclear.addClass('filter-out').fadeOut('fast'); 
     if(is_search !== 0) { 
      $('.filters').fadeOut(); 
     } 
    } 
}); 

$('.tag.remove-term').bind('click', function(){ 
    var $me = $(this), 
     mytext = $me.text(), 
     $myfilter = $('.filters .filter-clear:contains("'+ mytext +'")'); 

    doSomething($me); 
}); 

$searchedfor.find('.filter-clear').bind('click',function(){ 
    $searchedfor.fadeOut(); 
}); 
相關問題