How to sort a list of objects in JSP

爷,独闯天下 提交于 2020-01-17 11:39:54

问题


I have a list of items that will be shown to user. I know to sort the items I can send the list to back-end, sort them and show them again but how to do it in front-end so no need to send the list to back-end.

Ive found this table but it shows the results in columns. As you see I want to show them in a specific way as following.

<div class="row">
            <div class="col-md-4">
                <c:forEach var="item" items="${products}">
                    <div style="text-align: left;">
                      <div>
                         Name: ${item.name}
                      </div>
                      <div>
                        Price: ${item.price}
                      </div>
                   </div>
                 --------------------------
                </c:forEach>
            </div>
</div>

The output is not a table it would be like following

Name: item1
Price: 12
---------------
Name: item2
Price: 23
----------------

回答1:


You can sort the elements, take a look the example I did to sort by number:

http://jsfiddle.net/tnnqyxcw/1/

js:

$(document).ready(function(){
    $('button').on('click', function(){
        var s = $(this).data('sort'); console.log(s);
        if(s === 0){
            $(this).data('sort', 1);
            $('.clist div').sort(function(a,b){
               return a.dataset.sid < b.dataset.sid
            }).appendTo('.clist')            
        }else{
            $(this).data('sort', 0);
            $('.clist div').sort(function(a,b){
               return a.dataset.sid > b.dataset.sid
            }).appendTo('.clist')
        }
    });
});

Html

<button data-sort="0">Sort:</button><br>
<div class="clist">
    <div data-sid=1>Number 1</div>
    <div data-sid=4>Number 4</div>
    <div data-sid=3>Number 3</div>
    <div data-sid=1>Number 1</div>
    <div data-sid=4>Number 4</div>
    <div data-sid=2>Number 2</div>
    <div data-sid=1>Number 1</div>
</div>

So you can userdata- to sort for all you want and then assign the click to the button or whatever you want.

I hope it's help.



来源:https://stackoverflow.com/questions/29246769/how-to-sort-a-list-of-objects-in-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!