我试图在使用jquery ui sortable插件移动一行后,从带有标题类的tr中获取数据组,即一旦它被拖动到表中的新位置,我就需要访问close('tr.hading').data('group'),这样我就可以进行ajax调用来更新我的数据库。
无论我怎么尝试,data属性总是返回undefined。我可以 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);
});
你报告的另一个问题是你的表乱了,这是由上面函数中的第二行造成的,因为你基本上是把你的表元素换成了纯数字。
所以,你的函数中的第二行应该是 $(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>`);
最后回答你的最后一个问题 要想获得带有索引和标题的表的值 就用这段代码吧
console.log('product id = ' + $(ui.item).attr('data-some-id'));
console.log('Some Group = ' + $(ui.item).prevAll("tr.heading").first().attr("data-group"));
这是完整的解决方案 jsfiddle