开发者

Sort order of table tbody in same order as list elments jquery json

I have been working on this jsFiddle and wanted to extend the functionality so that when the list items have been altered and submitted via the form then the associated table tbodys sort themselves in the same order as their list item counterparts:

http://jsfiddle.net/8vWXZ/20/

Is it possible to map the order from one element to another li开发者_StackOverflowke this in jQuery?

I am not fussed about things animating but this new requirement has thrown me somewhat.


I didn't get what the ajax call was supposed to do, so I skipped that part. But the logic for resorting the table according to the list order is there, on the submit action of the form. I also reorganized how the tbody tag was used, since it didn't really serve a purpose to have each tr inside their own tbody tag.

Updated jsfiddle: http://jsfiddle.net/8vWXZ/24/

The code, to have it here on SO:
(#tableOrder is the table whose trs we are to reorder according to the order of the lis inside of ul#reOrder)

 $('#frmItems').submit(function() {

    var tbl = $("#tableOrder tbody");

    $("#reOrder li").each(function(index) {
        var li_id = $(this).attr("id");
        //Find the number of the item. Eg "item4" should result in "4"
        var li_item_number = li_id.match(/item([0-9]*)/)[1];
        //Inside #tableOrder, find the element (a <tr>) with id corresponding the this <li>'s id. Eg "item4"'s corresponding table row's id is "#tbl-item4"
        var correspondingTR = tbl.find("#tbl-item" + li_item_number);

        tbl.append(correspondingTR);
    });

I also did one more modifications. You had given both your li elements and tr elements the same ids (eg item1), which was bad (mmkay), since an ID should be unique. So i changed the trs inside tableOrder to have ids tbl-item1 and so on.

li_id.match(/item([0-9]*)/)[1] is a regex match. Basically, it searches for a pattern in the string and we can draw sertain sections out of that string. What it looks for is the pattern inside the slashes, so it's looking for something like itemX where X is a number ([0-9] says we are interested in any number from 0 to 9). It will return an array, and the item on index 1 is the number we are interested in.

About the append:
The .each goes through the lis, which are in the correct order. For each one, it adds the corresponding tr to the end of the table. Because all the trs in the table will be "touched", this means that it builds the order of the trs from scratch. The first tr to be appended, is the one on the top. The last one to be appended is the one on the bottom (as in, tr on spot n is appended in iteration n) I made two demos whose usefulnes is questionable, but you may find them helpful. http://jsfiddle.net/bGGRT/ and http://jsfiddle.net/bGGRT/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜