2014-04-17 74 views
0

我有一個創建一個多和少按鈕,在一個無序列表ID顯示越來越少的項目這個jQuery代碼=網格,其作品,但就是有點靠不住 目的:我總是希望顯示在摺疊/縮小狀態下附加列表,顯示更多按鈕以顯示列表中的更多項目jQuery的列表顯示更多顯示更少切換功能不可靠

但是,當新網格被添加到newImg時,它們有時在顯示所有狀態 反對摺疊狀態是存在使這種更可靠的在還原所附時總是顯示該網格的一方式/摺疊狀態示出了德更多按鈕

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');  
    }); 

} 

回答

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"); 
0

使用toggle()

添加的狀態變種職能以外的嘗試。

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); 
} 

然後,如果你改變的內容是指國家變種,如果它的關閉,添加內容之前再次運行切換功能。

我知道這應該對多個目標的工作,生病添加更多的時候,我家在這個問題上。在我的手機上。 :P

但基本上你將一個變種增加了更多收起功能的ID傳遞給它。抓住該元素,然後寫入一個新的數組元素到狀態var,我們將其設置爲數組而不是'false'。然後通過使用該ID,您可以爲每個目標設置一個狀態並引用它。

更新:增加了一個ID系統,它

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