How to display 5 more rows of a table on the click on a button using jQuery

后端 未结 2 2014
灰色年华
灰色年华 2020-12-31 14:18

I pre-load a table with all of its rows. However, I only want to show only the top 10 rows that are within the tag and now every <

2条回答
  •  一整个雨季
    2020-12-31 14:50

    1. You can use the selector $("#internalActivities tr") which will select all 's, regardless of a or not

    2. You need to save the current displayed index in a separate variable, or calculate the current index based on how many elements are selected (use the .length property)

    3. Check the current count of elements displayed and show/hide the corresponding buttons.

    Example

    HTML

    Javascript

    for (var i=0;i<21;i++) {
        $('#internalActivities').append('my data');
    }
    
    var trs = $("#internalActivities tr");
    var btnMore = $("#seeMoreRecords");
    var btnLess = $("#seeLessRecords");
    var trsLength = trs.length;
    var currentIndex = 10;
    
    trs.hide();
    trs.slice(0, 10).show(); 
    checkButton();
    
    btnMore.click(function (e) { 
        e.preventDefault();
        $("#internalActivities tr").slice(currentIndex, currentIndex + 10).show();
        currentIndex += 10;
        checkButton();
    });
    
    btnLess.click(function (e) { 
        e.preventDefault();
        $("#internalActivities tr").slice(currentIndex - 10, currentIndex).hide();          
        currentIndex -= 10;
        checkButton();
    });
    
    function checkButton() {
        var currentLength = $("#internalActivities tr:visible").length;
    
        if (currentLength >= trsLength) {
            btnMore.hide();            
        } else {
            btnMore.show();   
        }
    
        if (trsLength > 10 && currentLength > 10) {
            btnLess.show();
        } else {
            btnLess.hide();
        }
    
    }
    

    I created a jsFiddle demo to see this in action.

提交回复
热议问题