我试图说明页面上是否存在少于20个.news-item div,启用show more按钮。否则,如果有超过20个.news-items,则隐藏按钮。我的代码出了什么问题?
HTML:
<div class="news-item"></div>
<div class="news-item:hidden"></div>
<button class="btn show-more">Show More</button>
JS:
$(document).ready(function () {
var newsNum = $('.news-item').size();
console.log(newsNum);
$('.show-more').click(function () {
$('.news-item:hidden').slice(0,3).addClass('show');
$( ".news-item:hidden" ).slice( 0,5).removeClass("hidden");
if(newsNum >= 20) {
$(this).attr("disabled", true).hide();
}
else
{
$(this).attr("disabled", false);
}
});
});
答案 0 :(得分:0)
我真的不知道用户点击按钮会发生什么,但检查<div class="news-item">
数量很简单:
var newsItemsCount = $(".news-item").length;
var btnShowMore = $(".btn.show-more");
if (newsItemsCount >= 20) {
btnShowMore.show();
} else {
btnShowMore.hide();
}
您可以在所有必要的处理程序中使用它。
而且,是的,在标记中使用CSS类名news-item:hidden
是不正确的。
<强>更新强>
OK-OK!有一个消除歧义的词语“不正确”。我希望将之前的句子重写为“尽量避免使用CSS类名news-item:hidden
”。他们只是让你的jQuery代码更复杂,没有任何功能上的好处。这是一个简单的例子:jsFiddle。
答案 1 :(得分:0)
没有这样的:hidden
Bootstrap课程: See for yourself
应该是.hidden
$(document).ready(function () {
var $newsAll = $('.news-item');
var newsAllTotal = $newsAll.length;
var $newsVisible = $newsAll.not(".hidden");
var newsVisibleTotal = $newsVisible.length;
var incrementBy = 3; // Reveal 3-by-3
$('.show-more').click(function () {
newsVisibleTotal += incrementBy;
$newsAll.slice(0, newsVisibleTotal).addClass('show');
$(this).toggle( newsAllTotal-1 >= newsVisibleTotal );
});
});
&#13;
[class^=news-item]{
background:#eee;
padding:10px;
margin:3px;
}
[class$=hidden]{
display:none;
}
.show{
display:block !important;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="news-item">1</div>
<div class="news-item">2</div>
<div class="news-item">3</div>
<div class="news-item hidden">4</div>
<div class="news-item hidden">5</div>
<div class="news-item hidden">6</div>
<div class="news-item hidden">7</div>
<div class="news-item hidden">8</div>
<div class="news-item hidden">9</div>
<div class="news-item hidden">10</div>
<div class="news-item hidden">11</div>
<div class="news-item hidden">12</div>
<div class="news-item hidden">13</div>
<div class="news-item hidden">14</div>
<div class="news-item hidden">15</div>
<div class="news-item hidden">16</div>
<button class="btn show-more">Show More</button>
&#13;