Jquery列表显示更多显示更少切换功能不可靠

时间:2014-04-17 06:59:01

标签: jquery toggle

我有这个jquery代码创建一个越来越少的按钮来显示无序列表id = grid中的越来越少的项目,但是有点不可靠 目标:我总是希望显示在折叠/缩小状态下附加列表,并显示更多按钮以显示列表中的更多项目

然而,当新网格附加到newImg时,它们有时处于show all状态 与折叠状态相反的是,有一种方法可以使得更加可靠,以便在缩小/折叠状态下显示网格时显示更多按钮

  newImg.appendChild(grid);

  $('#grid').each(function() {
   var $list = $(this);
    $list.before('<button class="more_less">More</button>');
  $list.find('.grid-item:gt(2)').hide();
  });


   $('.more_less').click(function() {
  var $btn = $(this);
  $btn.next().find('.grid-item:gt(2)').slideToggle();    
   $btn.text($btn.text() == 'More' ? 'Less' : 'More');    
  });

 }

2 个答案:

答案 0 :(得分:0)

尝试使用toggle()

在函数外添加状态var。

var state = new Array(),
    moreLess = function(id){ // IDs are class names
    $('.' + id).toggle(function(){
         state[id] = true;
         // show all code
     },
     function(){
         state[id] = false;
         // hide code
    });
});

// ...

var elm = $('.example-class'),
    class = elm.attr('class'); // example of fetching state id from element
if ( state[ class ] == false )  { // you check with this before adding content
    moreLess( class );
}

然后,如果您更改内容,请参阅状态var,如果已关闭,请在添加内容之前再次运行切换功能。

我意识到这应该适用于多个目标,当我在这个主题上回家时会添加更多。在我的手机上。 :P

但基本上你会在moreLess函数中添加一个var来传递一个id。抓取该元素,然后将新的数组元素写入我们设置为数组的状态var而不是&#39; false&#39;。然后,通过使用该ID,您可以为每个目标设置状态并引用它。

更新:为其添加了ID系统

https://api.jquery.com/toggle/

答案 1 :(得分:0)

如果要添加多个网格,请确保使用的是类名而不是id(因为id必须是唯一的,不得被其他元素使用),并创建一个可重用的函数,将网格附加到容器,并将动态创建更多/更少按钮。

//Here is a reusable function that takes two parameter:
//container: an element that will contain the ul list, in your case newImg
//grid: ul element
function createGrid(container, grid)
{
      $(container).append(grid);

      $(grid).before('<button class="more_less">More</button>');
      $(grid).find('.grid-item:gt(2)').hide();

      $('.more_less').click(function() {
         var $btn = $(this);
         $btn.next().find('.grid-item:gt(2)').slideToggle();    
         $btn.text($btn.text() == 'More' ? 'Less' : 'More');    
      });
}


$(body).ready(function(){
                            $(".grid").each(function(index, grid){ createGrid($("#newImg"), grid) });
                         });

//This  line of code will iterate for each element with class ".grid" and pass it to createGrid function

对于在执行上一个代码后创建的新网格,只需使用该函数。

createGrid($("#newImg"), $("#new-grid");
相关问题