문제

This question has been asked long ago and answered as well here jQuery load first 3 elements, click “load more” to display next 5 elements, but that was for only one ul element.

However, I want to know how to do the same thing for multiple elements say I have this instead:

<ul id="myList"></ul>
<ul id="myList1"></ul>
<ul id="myList2"></ul>

how do I make the javascript for multiple elements in this case??

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});  

any idea how to do that??

Thanks

Update#1:

This is my other code part for showmore and showless

<div id="loadMore">Load more</div><div id="showLess">show Less</div>

Update#2

what if classes used instead of ids, would that make it easier?? like this:

    <ul class="myList"></ul>
    <ul class="myList"></ul>
    <ul class="myList"></ul>

and each showmore/Less can control one of them. so one to one... is that possible???

도움이 되었습니까?

해결책

You can change your code by using classes instead of ids and a wrapping div; than change accordingly the logic by using element nesting.

Instead of use a variable you can use a HTML attribute to store the current number of showed li for each ul.

Code:

$(document).ready(function () {

    $(".wrapper").each(function (index) {
        $(this).find('.myList li:lt(' + $(this).attr('viewChild') + ')').show();
    });   

    $('.loadMore').click(function () {
        var $myWrapper= $(this).closest('.wrapper');
        var x= parseInt($myWrapper.attr('viewChild'),10);
        var liSize=$myWrapper.find('.myList li').size();        
        x = (x + 5 <= liSize) ? x + 5 : liSize;
        $myWrapper.attr('viewChild',x)
        $myWrapper.find('.myList li:lt(' + x + ')').show();
        $myWrapper.find('.showLess').show();
        if (x == liSize) {
            $myWrapper.find('.loadMore').hide();
        }
    });

    $('.showLess').click(function () {
        var $myWrapper= $(this).closest('.wrapper');
        var x= $myWrapper.attr('viewChild')
        x = (x - 5 < 0) ? 3 : x - 5;
        $myWrapper.attr('viewChild',x)
        $myWrapper.find('.myList li').not(':lt(' + x + ')').hide();
        $myWrapper.find('.loadMore').show();
        $myWrapper.find('.showLess').show();
        if (x == 3) {
            $myWrapper.find('.showLess').hide();
        }
    });
});

Demo: http://jsfiddle.net/9gxBT/

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top