jQuery UI 移动后可排序的最近元素 class

jQuery UI Sortable closest element with class after move

在使用 jquery ui sortable 插件。也就是说,一旦它被拖到 table 中的新位置,我就需要访问最近的('tr.heading').data('group'),这样我就可以进行 ajax 调用更新我的数据库。

无论我怎么尝试,数据属性总是 returns 未定义。我可以 console.log data-some-id 所以我知道我可以访问该元素。

这里是jsfiddle

<table id="sort">
<tbody>
<tr class="heading" data-group="1" data-something-else="2">
   <td colspan="4">Group 1</td>
</tr>
<tr data-some-id="1" class="index">
   <td>Some Id</td>
   <td>Some Name</td>
   <td>Some description</td>
   <td>Some action</td>
</tr>
<tr data-some-id="2" class="index">
   <td>Some Id 2</td>
   <td>Some Name 2</td>
   <td>Some description 2</td>
   <td>Some action 2</td>
</tr>
<tr data-some-id="3" class="index">
   <td>Some Id 3</td>
   <td>Some Name 3</td>
   <td>Some description 3</td>
   <td>Some action 3</td>
</tr>
<tr class="heading" data-group="2" data-something-else="2">
   <td colspan="4">Group 2</td>
</tr>
<tr data-some-id="4" class="index">
   <td>Some Id 4</td>
   <td>Some Name 4</td>
   <td>Some description 4</td>
   <td>Some action 4</td>
</tr>
<tr data-some-id="5" class="index">
   <td>Some Id 5</td>
   <td>Some Name 5</td>
   <td>Some description 5</td>
   <td>Some action 5</td>
</tr>
<tbody>
</table>

<script>
var fixHelperModified = function(e, tr) {
        var originals = tr.children();
        var helper = tr.clone();
        helper.children().each(function(index) {
            $(this).width(originals.eq(index).width())
        });
        return helper;
    },
    updateIndex = function(e, ui) {

        $('td.index', ui.item.parent()).each(function (i) {
            $(this).html(i + 1);
        });

        console.log('product id = ' +  $(ui.item).attr('data-some-id'));
        console.log('Some Group = ' + $(ui.item).closest(".heading").attr("data-group"));
    }

   $("#sort tbody").sortable({
     helper: fixHelperModified,
     stop: updateIndex
   }).disableSelection();
</script>

起初我不明白你在找什么,所以这是更新后的正确解决方案。

是的,您的初始选择器是错误的,因此在将 td 更改为 tr 后,排序功能开始起作用。

$('tr.index', ui.item.parent()).each(function (i) {
    $(this).html(i + 1);
});

您报告的另一个问题是您的 table 搞砸了,这是由上述函数中的第二行引起的,因为您基本上将 table 元素替换为纯数字。

因此,我将行 $(this).html(i + 1) 替换为以下代码部分:

$(this).html(`
    <tr data-some-id="${i + 1}" class="index">
        <td>Some Id ${i + 1}</td>
        <td>Some Name ${i + 1}</td>
        <td>Some description ${i + 1}</td>
        <td>Some action ${i + 1}</td>
    </tr>`);

最后回答你的最后一个问题,要获取索引和标题为 类 的 table 行的值,请使用此代码:

console.log('product id = ' +  $(ui.item).attr('data-some-id'));
console.log('Some Group = ' + $(ui.item).prevAll("tr.heading").first().attr("data-group"));

这是完整的解决方案 - jsfiddle