简体   繁体   中英

jQuery selector caching issue

The problem is, when I wrote every time HTML tags' ids the code below works. But when I cache them, it doesn't. What am I missing?

Here is my code:

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");
    });
});

BTW, no error in console. And I'm using jQ-UI too

You need to cache them when the dom is ready.

$(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");
    });
});

When you cache them, they're being evaludated before document.ready. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM