如何显示/隐藏一定数量的div?

时间:2016-05-12 15:59:08

标签: javascript jquery jquery-selectors append

我在尝试显示/隐藏一定数量的div时遇到问题。我有一个动态div创建,将打印所有内容,但隐藏在第5 div之后的任何内容。然后,如果我单击“加载更多”按钮,它将显示全部和“显示更少”,仅显示前五个div。我尝试了这个,但没有奏效。这是jsfiddle.

var vidThumbnail = "";
for(i = 0, i < 25, i++)
{
  vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';

    // if the child elements reaches 5 thumbnails, hide the rest
  if($('.section.thumbnail .thumb > .video-thumbnail:gt(5)'))
  {
      $('.section.thumbnail .thumb').append(vidThumbnail).hide();
  }
  else 
  {
      $('.section.thumbnail .thumb').append(vidThumbnail).slice(0,5);
  }
}

$('#loadMore').click(function() // show them all
{
    $('.section.thumbnail .thumb').show();
});

$('#showLess').click(function() // hide all up to the first 5 thumbnails
{ 
    $('.section.thumbnail .thumb > .video-thumbnail').slice(0,5);
});

<section class="section thumbnail">
    <h1>Thumbnail Divs</h1>
    <div class="thumb"></div>
    <div id="loadMore">Load More</div>
    <div id="showLess">Show Less</div>
</section>

2 个答案:

答案 0 :(得分:0)

你的原始小提琴在for循环中使用逗号而不是分号,因此初始脚本失败了 - 然后它产生的dom并不是你的选择器所期望的。

以下是我解决问题的方法:

https://jsfiddle.net/9pcp72bk/3/

var vidThumbnail = "";

var hideAdditionalThumbs = function() {
    var elements = $('.section.thumbnail .thumb > .video-thumbnail');
    for (var i = 5; i < elements.length; i++) {
      $(elements[i]).hide();
    }
};

$('#loadMore').click(function() // show them all
  {
    $('.section.thumbnail .thumb .video-thumbnail').show();
  });

$('#showLess').click(hideAdditionalThumbs);

for (i = 0; i < 25; i++) {
  vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';

    $('.section.thumbnail .thumb').append(vidThumbnail);
        hideAdditionalThumbs()
}

答案 1 :(得分:0)

我对您的代码进行了一些编辑,现在正在运行:https://jsfiddle.net/IA7medd/hc5pL6ju/

var vidThumbnail = "";
for(i = 0; i < 25; i++)
{
  vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
  $('.section.thumbnail .thumb').append(vidThumbnail);

    // if the child elements reaches 5 thumbnails, hide the rest
  if(i>5) {
      $('.video-thumbnail').eq(i).hide();
  }
}

$('#loadMore').click(function() // show them all
{
    $('.video-thumbnail').show();
});

$('#showLess').click(function() // hide all up to the first 5 thumbnails
{ 
    for(i=5; i<25; i++){
        $('.video-thumbnail').eq(i).hide();
  }
});