簡體   English   中英

停止排序並使用 Javascript 重新定位 tr

[英]Stop the sorting and reposition the tr using Javascript

單擊模式中的取消按鈕后,我想停止排序並使用 Javascript 重新定位 tr。 但是當我運行以下代碼時,出現錯誤,

未捕獲的錯誤:無法在初始化之前調用 sortable 上的方法; 試圖調用方法“取消”

模態:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria- 
 labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           <span aria-hidden="true">&times;</span>
        </button>
      </div>
  <div class="modal-body">
    Do you really want to update the order?
  </div>
  <div class="modal-footer">
    <button id="cancel_update_order" type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    <button id="update_order" type="button" class="btn btn-primary">Save changes</button>
  </div>
</div>

腳本:

new Tablesort(document.getElementById('table'));

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) {
    $('#exampleModal').modal({
      backdrop: 'static',
      keyboard: false
    })

    $('#update_order').on('click', function() {
      $('td.index', ui.item.parent()).each(function (i) {
          $(this).html(i + 1);
      });
      $('#exampleModal').modal('hide');
    });

    $('#cancel_update_order').on('click', function() {
      $(this).sortable('cancel');
    });

  };

$("#table tbody").sortable({
  helper: fixHelperModified,
  stop: updateIndex
}).disableSelection();

當您收到此錯誤時:

未捕獲的錯誤:無法在初始化之前調用 sortable 上的方法; 試圖調用方法“取消”

這很可能意味着您在與初始化排序的元素不同的元素上調用“取消”。

在這種情況下,您有以下代碼:

$('#cancel_update_order').on('click', function() { 
    $(this).sortable('cancel'); 
}); 

在該代碼中,“this”指的是cancel_update_order,按鈕,而不是表格。

如果您只有一個 sortable(使用外部方法updateIndex那么可以通過引用已初始化的 sortable 表來快速解決此問題:

$('#cancel_update_order').on('click', function() { 
    $("#table tbody").sortable('cancel'); 
}); 

如果您希望它更可重用,那么您需要在引用表時保留“this”的副本:

updateIndex = function(e, ui) {

    var sortableElement = this;

    $('#cancel_update_order').on('click', function() {
      $(sortableElement).sortable('cancel');
    });

  };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM