Jquery 计数 each() 第一项返回未定义
Jquery count each() first item coming back as undefined
如果 ul 中的 li 少于 5 行,我将尝试隐藏 "Show All" 按钮,但第一个 ul 返回时未定义,因此它仅对其余部分有效。谁能告诉我我的代码有什么问题?提前致谢...
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)
});
正如评论中指出的那样,您的 len
从未在 each
的第一次迭代中定义
有几种方法可以删除 count
变量。
首先,$(selector).each(function(index, element){/* code */})
$.each
已经为您跟踪索引。该索引将与您的 count
相同
另一种方法,因为您的代码想要跳过第一个匹配元素,所以在第一个元素之后使用 'gt()'
选择器
开始 each
// 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)
});
如果 ul 中的 li 少于 5 行,我将尝试隐藏 "Show All" 按钮,但第一个 ul 返回时未定义,因此它仅对其余部分有效。谁能告诉我我的代码有什么问题?提前致谢...
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)
});
正如评论中指出的那样,您的 len
从未在 each
有几种方法可以删除 count
变量。
首先,$(selector).each(function(index, element){/* code */})
$.each
已经为您跟踪索引。该索引将与您的 count
另一种方法,因为您的代码想要跳过第一个匹配元素,所以在第一个元素之后使用 'gt()'
选择器
each
// 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)
});