在我的排序脚本中理解get()的用法

时间:2015-04-16 07:47:37

标签: javascript jquery

我最近发现了一个我真想了解的代码片段:

var buttons = $('#fruit,#vegetable,#meat').click(function() {
    $(this).toggleClass('active');
    var classes = buttons.filter('.active').map(function() {
        return this.id;
    }).get().join(',.');
    $('div.fruit,div.vegetable,div.meat').hide().
        filter('.' + (classes || 'none')).show();
});

HTML代码:

<div style="float:right; padding:25px;">
    <button id="fruit" class="active"><span>fruit</span></button>
    <button id="vegetable" class="active">vegetable</button>
    <button id="meat" class="active">meat</button>
</div>

<div>
       <p>Trying to use buttons as an "or" case rather than "and." When choosing fuit or vegetable, I want to see tomato as part of each list, <em>not just</em> when both are selected.</p>  

<div class="fruit">
    <p>apple</p>
</div>

<div class="vegetable">
    <p>pumpkin</p>
</div>

<div class="vegetable">
   <p>okra</p>
</div>

<div class="fruit">
    <p>orange</p>
</div>

<div class="meat">
    <p>beef</p>
</div>    


<div class="fruit vegetable">
    <p>tomato</p>
</div>    

</div>

小提琴是here

我确实理解jQuery中所有方法的工作方式如toggleclassfiltermap,我也理解join如何在JS中工作,但在这个特定的例子中,我无法弄清楚get()是如何工作的,或者说它在脚本中的用法是什么。

我浏览了get()的jQuery文档,我第一次遇到了这种方法;对我而言,它似乎与jQuery中的eq()非常相似,但我仍然无法弄清楚为什么在我的示例中使用了get

有人可以向我解释一下吗?

1 个答案:

答案 0 :(得分:2)

这里使用

.get,因为.map返回一个jquery样式对象,其中包含一些函数和有关所包含数据的信息。但在这种情况下,只需要存储在对象中的值(活动按钮的类名)。 .get用于获取包含原始值的数组,并使用.join(",.")将数组中的值连接到字符串。然后,该字符串用于显示根据所选按钮应该处于活动状态的所有div。