Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Getting an empty JQuery object

In the following code I set up a change handler on a select box to show and hide some follow up questions based on the value of the selection.

Further, for some values of the selection there is an extra message that is displayed.

In order to check to see if I need to hide the extra message, I keep a variable called Previous. Upon execution of the handler I check to see if Previous is null or if the size is 0.

It would be nice to initialize Previous to an empty JQuery object so as not to have to do the extra check for null.

Doing a $() returns an object with the size of 1.

Is there a way to create an empty Jquery object?

//Init function.
$(function(){
//Hold the previously selected object for the account type selection.

var Previous = null;  //Here is where I would like to initialize.
                      //something like Previous = $();


$("SELECT[name='AccountType']").change(
    function () {
        //Hide Previous message if there was one.
        if(Previous == null || Previous.size() > 0){ 
            Previous.hide();
        }

        //Show the message if found and save it as previous.
        Previous = $("#"+this.value+"_Msg").show();

        //Get fisrt question
        var FirstQuestion = $(".FirstQuestion");
        if(this.value === ''){
            FirstQuestion.hide();
        }else{
            //Manually show FirstQuestion.
            FirstQuestion.show();
        }
    });
}

In the worst case I could do something like this:

    var Previous = { size : function () { return 0; } };

but that seems like overkill.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This creates an empty jQuery-object:

$([])

Update: In newer versions of jQuery (1.4+), you can use:

$()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...