2009-05-22 43 views
106

在以下代码中,我在选择框上设置了更改处理程序,以根据选择的值显示和隐藏一些后续问题。获取空的JQuery对象

此外,对于选择的某些值,还会显示一条额外的消息。

为了检查是否需要隐藏额外的消息,我保留一个名为Previous的变量。在执行处理程序时,我检查前面是否为空或大小为0.

初始化上一个空的JQuery对象以便不必执行额外的空值检查会很好。

做一个$()返回的1

大小的物体有没有一种方法创建一个空的jQuery对象?

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

在最坏的情况下,我可以做这样的事情:

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

,但似乎有点小题大做。

回答

197

这将创建一个空的jQuery对象:

​​

更新: 在jQuery中(1.4+)的新版本,你可以使用:

$() 
+6

+1可爱的回答,我决不会已经想到这一点:) – 2010-05-27 12:32:51

+0

我不明白这是怎么从`$()不同`。任何人都可以投射灯光? – cregox 2011-03-02 00:40:15

3

我的建议是不要”不要这样做。有很多简单的方法来做到这一点。试想一下:

<select id="select" name="select"> 
    <option value="msg_1">Message 1</option> 
    <option value="msg_2">Message 1</option> 
    <option value="msg_3">Message 1</option> 
</select> 

<div class="msg_1 msg_3"> 
    ... 
</div> 

<div class="msg_1"> 
    ... 
</div> 

<div class="msg_2"> 
    ... 
</div> 

$(function() { 
    $("#select").change(function() { 
    var val = $(this).val(); 
    $("div." + val").show(); 
    $("div:not(." + val + ")").hide(); 
    }); 
}); 

许多容易。基本上给班级指出要显示和隐藏的内容,然后不需要跟踪。另一种方法是:

$(function() { 
    $("#select").change(function() { 
    var val = $(this).val(); 
    $("div").each(function() { 
     if ($(this).hasClass(val)) { 
     $(this).show(); 
     } else { 
     $(this).hide(); 
     } 
    }); 
    }); 
}); 
19
$(); 

返回一个空集

对于jQuery 1.4,调用jQuery()方法不带参数返回一个空的jQuery集(为0的.length属性)。在之前的jQuery版本中,这将返回一个包含文档节点的集合。

来源:api.jquery.com