javascript jQuery 中的自定义数据可排序吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8260107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:49:21  来源:igfitidea点击:

Custom data in jQuery sortable?

javascriptjqueryjquery-ui-sortable

提问by Alex

on the "update" callback you can get the order of elements with $(this).sortable('toArray');

在“更新”回调中,您可以获得元素的顺序 $(this).sortable('toArray');

But this order contains the element IDs.

但此订单包含元素 ID。

How can I get a custom attribute, like data-myattr? I want that order to contain values from this attibute instead of IDs....

如何获得自定义属性,例如data-myattr?我希望该订单包含来自此属性的值而不是 ID....

   $('ul').sortable({
     handle: 'h2'
     items: 'li',
     context: this,
     update: function(){        

       var order = $(this).sortable('toArray');

       // here I want a array of values from my attribute, not ID values...
       alert(order);

       ....

     }
   });

The HTML is simple:

HTML 很简单:

<ul>
  <li data-myattr="a-1" id="whatever">
    ...
  </li>
  ...

采纳答案by Luke Girvin

$("ul").sortable({
  .
  .
  .
  update: function(event, ui) {        
    var arr = $(this).sortable('toArray');
    var i, n;
    var attrs = [];
    for (i = 0, n = arr.length; i < n; i++) {
      attrs.push($('#' + arr[i]).data('myattr'));
    }

    alert(attrs);  
  }
});

回答by julien_c

As of August '12, this is implemented directly in jQuery UI:

截至 12 年 8 月,这是直接在 jQuery UI 中实现的:

var order = $(this).sortable('toArray', {attribute: 'data-myattr'});

回答by Alper

$("li").data("myattr") // if you use jQuery, >= 1.4.3

$("li").attr("data-myattr") // for erlier

JS Fiddle here

JS小提琴在这里