Jquery将每个()第一个项目计为未定义

时间:2015-01-28 18:26:58

标签: jquery show-hide

我试图隐藏一个“全部显示”按钮,如果ul中的li少于5 li但是第一个ul返回为undefined,那么它只适用于其余的。谁能告诉我我的代码有什么问题?提前谢谢......

    var count = 0;
    $('article ul').each(function () {
        if (count != 0) {
            var len = $(this).find('li').length;

            if (len < 5) {
                $(this).parent().find('.viewAll').hide();
            }
        }
        count++;
        console.log(len)
    });

1 个答案:

答案 0 :(得分:1)

正如评论中所指出的那样,len的第一次迭代中永远不会定义each

有几种方法可以摆脱count变量。

首先,$(selector).each(function(index, element){/* code */})

$.each已经为您跟踪索引。此索引与您的count

相同

另一种方式,因为您的代码想要跳过第一个匹配元素是使用each选择器

在第一个匹配元素之后启动'gt()'
// gt(0) will start after first element of matching selector
$('article ul:gt(0)').each(function () {    
    var len = $(this).find('li').length;    
    if (len < 5) {
        $(this).parent().find('.viewAll').hide();        
    }    
    console.log(len)
});