简体   繁体   English

jQuery选择器缓存问题

[英]jQuery selector caching issue

The problem is, when I wrote every time HTML tags' ids the code below works. 问题是,当我每次写HTML标签的ID时,下面的代码都有效。 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 我也在使用jQ-UI

You need to cache them when the dom is ready. 你需要在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");
    });
});

When you cache them, they're being evaludated before document.ready. 当你缓存它们时,它们会在document.ready之前被评估。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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