2012-09-04 54 views
1

問題是,當我每次寫HTML標籤的ID時,下面的代碼都起作用。但是,當我緩存它們時,它不會。我錯過了什麼?jQuery選擇器緩存問題

這裏是我的代碼:

var NewFormContainer=$("#NewUserFormContainer"), opener=$("#nufcOpen"), closer=$("#nufcClose"), NewForm=$("#NewUserForm"); 
$(function() { 
    $("#userType").buttonset(); 
    $(".btn").button(); 

    closer.button({ 
     icons: { 
      primary: "ui-icon-closethick" 
     }, text: false 
    }).click(function(){ 
     NewFormContainer.slideUp("slow"); 
    }); 
    opener.click(function(){ 
     NewFormContainer.slideDown("slow"); 
    }); 
}); 

順便說一句,在控制檯沒有錯誤。而且我也使用jQ-UI

回答

1

當你緩存它們時,它們會在document.ready之前被評估。試試這個:

var NewFormContainer="#NewUserFormContainer", opener="#nufcOpen", closer="#nufcClose", NewForm="#NewUserForm"; 
$(function() { 
    opener = $(opener); 
    closer = $(closer); 
    NewFormContainer = $(NewFormContainer); 
    NewForm = $(NewForm); 
    ... 
2

dom準備就緒時,您需要cache

$(function() { 
    $("#userType").buttonset(); 
    $(".btn").button(); 

    var NewFormContainer=$("#NewUserFormContainer"), 
     opener=$("#nufcOpen"), 
     closer=$("#nufcClose"), 
     NewForm=$("#NewUserForm"); 

    closer.button({ 
     icons: { 
     primary: "ui-icon-closethick" 
     }, text: false 
    }).click(function(){ 
     NewFormContainer.slideUp("slow"); 
    }); 

    opener.click(function(){ 
     NewFormContainer.slideDown("slow"); 
    }); 
});