我试图隐藏一个“全部显示”按钮,如果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)
});
答案 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)
});