0

扩展:https ://stackoverflow.com/a/31047/235633

有没有办法可以扩展这个自定义 jQuery 函数以使用回调?本质上,我希望能够拥有一个选择器列表并检测它们的存在,如果它们存在,我需要显示它们。

与其编写一千个 if 语句,我更愿意编写一个使用回调和“this”的函数。

那家伙写道:

jQuery.fn.exists = function(){return this.length>0;}

if ($(selector).exists()) {
    // Do something
}

但是我需要:

$('.selector1, .selector2, .selector3').exists(function({
    $(this).show();
});
4

3 回答 3

3

所以基本上,你想展示那些存在的?那么你不需要:)

$('.selector1, .selector2, .selector3').show();
于 2011-12-22T16:52:32.627 回答
3

jQuery 会为你循环遍历它们。

$('.selector1, .selector2, .selector3').show();

应该按预期工作。

于 2011-12-22T16:52:13.037 回答
0

在一般情况下,您可以为此使用.each

$('.selector1, .selector2, .selector3').each(function({
  //some work involving $(this) 
});

但在这种情况下,无论如何,show都适用于所有匹配的元素:

$('.selector1, .selector2, .selector3').show();
于 2011-12-22T16:51:09.323 回答