简体   繁体   中英

Sorting Divs With JQuery Based On “data-” Attribute

I'm trying to sort divs using jquery based on it's data-enter attribute. Here's my JQuery for it:

            let result = $("#tableEls .dataDiv").sort(function (a, b) {
                console.log(+$(a).data("enter") + " < " + +$(b).data("enter"));
                return +$(a).data("enter") < +$(b).data("enter");
            }).appendTo("#tableEls");

            console.log(result);

However, when this is called, it doesn't reorder the divs. Here are the divs:

我正在尝试排序的 Div。

Also, here's the console output:

控制台输出

I've tried many different solutions on StackOverflow but can't find any that work for me. I'm not sure if I'm doing something wrong but I can't see anything wrong.

Also, here's the screenshot of the HTML page itself with each of the four divs outlined with a black border:

HTML页面

When the Sort Rows button is clicked, the enter cell from each table and adds it as the data-enter attribute for each div before running the JQuery from above. So in this example, the first and second div's positions should be swapped.

your sort function have to return N or -N or 0 not a boolean:

let result = $("#tableEls .dataDiv").sort(function (a, b) {
            console.log(+$(a).data("enter") + " - " + +$(b).data("enter"));
            return +$(a).data("enter") - +$(b).data("enter");
        }).appendTo("#tableEls");

        console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM