简体   繁体   English

使用基于“data-”属性的 JQuery 对 Div 进行排序

[英]Sorting Divs With JQuery Based On “data-” Attribute

I'm trying to sort divs using jquery based on it's data-enter attribute.我正在尝试使用 jquery 根据它的data-enter属性对 div 进行排序。 Here's my JQuery for it:这是我的 JQuery:

            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.但是,当它被调用时,它不会对 div 重新排序。 Here are the divs:以下是div:

我正在尝试排序的 Div。

Also, here's the console output:此外,这是控制台输出:

控制台输出

I've tried many different solutions on StackOverflow but can't find any that work for me.我在 StackOverflow 上尝试了许多不同的解决方案,但找不到任何适合我的解决方案。 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 页面本身的屏幕截图,其中四个 div 中的每一个都带有黑色边框:

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.当单击Sort Rows按钮时,在从上面运行 JQuery 之前,从每个表中输入单元格并将其添加为每个 div 的数据输入属性。 So in this example, the first and second div's positions should be swapped.所以在这个例子中,第一个和第二个 div 的位置应该交换。

your sort function have to return N or -N or 0 not a boolean:您的排序函数必须返回 N 或 -N 或 0 而不是布尔值:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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