首页 > 解决方案 > 使用 <输入> 的 jQuery UI 可排序位置

问题描述

此表http://jsfiddle.net/rp4fV/477/具有输入元素,我需要对行添加数字进行排序并获得拖动结果,例如,如果我将 2 输入到第 4 行,则第 4 行会自动起床以替换第 2 行和所有行的排序取决于新的更改,有什么建议如何做到这一点吗?我知道如何使用拖动来做到这一点,但使用输入我不知道如何做到这一点。

原因是有很多行,有时拖动时我无法识别正确的位置。

代码:

$('td, th', '#sortFixed').each(function () {
  var cell = $(this);
 cell.width(cell.width());
});
$('#sortFixed tbody').sortable().disableSelection();

标签: jqueryjquery-uijquery-ui-sortable

解决方案


您需要oninput在执行操作后将输入元素绑定到事件

// Fix the width of the cells

$('td, th', '#sortFixed').each(function() {
  var cell = $(this);
  cell.width(cell.width());
});

$('#sortFixed tbody').sortable().disableSelection();

$('body').on('input', 'input[type="text"]', function() {
  $('tbody tr').removeClass('marker');
  var currentEl = $(this);
  var index = parseInt(currentEl.val());
  if (index <= $('input[type="text"]').length) {
    currentEl.attr('value', index)
    var oldLoc = currentEl.parent().parent()
    var newLoc = $('tbody tr').eq(index-1)
    newLoc.addClass('marker')
    var newLocHtml = newLoc.html()
    newLoc.html(oldLoc.html()).hide().fadeIn(1200);
    oldLoc.html(newLocHtml)
  }
})
tbody tr {
  cursor: move
}

.marker {
  background: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-ui-dist@1.12.1/jquery-ui.min.js"></script>

<table id="sortFixed" class="grid">
    <caption>Kurt Vonnegut novels</caption>
    <thead>
        <tr><th>Order</th><th>Year</th><th>Title</th><th>Grade</th></tr>
    </thead>
    <tbody>
        <tr><td><input type="text" id='ordem_0' name="order"></td><td>1969</td><td>Slaughterhouse-Five</td><td>A+</td></tr>
        <tr><td><input type="text" id='ordem_1' name="order"></td><td>1952</td><td>Player Piano</td><td>B</td></tr>
        <tr><td><input type="text" id='ordem_2' name="order"></td><td>1963</td><td>Cat's Cradle</td><td>A+</td></tr>
        <tr><td><input type="text" id='ordem_3' name="order"></td><td>1973</td><td>Breakfast of Champions</td><td>C</td></tr>
        <tr><td><input type="text" id='ordem_4' name="order"></td><td>1965</td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr>
    </tbody>
</table>


推荐阅读