2010-08-16 106 views
1

該函數被寫入兩次以保存複選框狀態以及相應的div文本。我該如何在函數中編寫代碼,然後在加載時分別調用它兩次並分別單擊事件?避免jQuery中的函數重複

$(document).ready(function() { 
        $("#bquote").load("quotes_in.php", function() { 

        // a key prefix is used for the cookie/storage 
        var storedData = getStorage('com_mysite_checkboxes_'); 

        $('div.check input:checkbox').bind('change',function(){ 
        $('#ab_' + this.id).toggle($(this).is(':checked')); 

        // save the data on change 
        storedData.set(this.id, $(this).is(':checked')?'checked':'not'); 
        }).each(function() { 

        // on load, set the value to what we read from storage: 
        var val = storedData.get(this.id); 
        if (val == 'checked') $(this).attr('checked', 'checked'); 
        if (val == 'not') $(this).removeAttr('checked'); 
        if (val) $(this).trigger('change'); 

        }); 
       });     

      }); 



      $(function() { 


      /*load quotes on click of link*/ 
      $("a#main") 
       .click(function() { 
        $(this).addClass("current"); 
        $("#bquote").load("quotes_in.php", function() { 

        // a key prefix is used for the cookie/storage 
        var storedData = getStorage('com_mysite_checkboxes_'); 

        $('div.check input:checkbox').bind('change',function(){ 
        $('#ab_' + this.id).toggle($(this).is(':checked')); 

        // save the data on change 
        storedData.set(this.id, $(this).is(':checked')?'checked':'not'); 
        }).each(function() { 

        // on load, set the value to what we read from storage: 
        var val = storedData.get(this.id); 
        if (val == 'checked') $(this).attr('checked', 'checked'); 
        if (val == 'not') $(this).removeAttr('checked'); 
        if (val) $(this).trigger('change'); 

         });  
       }); 
      }); 

回答

2

可以作爲一個命名函數聲明一次,並調用它兩次,這樣的:

$(function() { 
    function loadQuotes() { 
    $("#bquote").load("quotes_in.php", function() { 

     // a key prefix is used for the cookie/storage 
     var storedData = getStorage('com_mysite_checkboxes_'); 

     $('div.check input:checkbox').bind('change',function(){ 
     $('#ab_' + this.id).toggle(this.checked); 

     // save the data on change 
     storedData.set(this.id, this.checked?'checked':'not'); 
     }).each(function() { 

     // on load, set the value to what we read from storage: 
     var val = storedData.get(this.id); 
     if (val == 'checked') $(this).attr('checked', 'checked'); 
     if (val == 'not') $(this).removeAttr('checked'); 
     if (val) $(this).trigger('change'); 

     }); 
    });     
    } 
    $("a#main").click(function() { 
    $(this).addClass("current"); 
    loadQuotes(); 
    }); 
    loadQuotes(); //call it once on load 
}); 

我在上面也改變$(this).is(':checked')this.checked,沒有必要讓它越慢,DOM物業在這裏工作:)

+0

非常感謝! – input 2010-08-16 18:26:28