javascript - jQuery 可排序序列化无法识别动态添加的内容

标签 javascript jquery ajax

我正在尝试通过ajax在可排序更新上重新排序列表,但是在可排序已经在页面加载时初始化后通过ajax将新项目添加到此列表后,它无法识别带有“序列化”的新项目“功能。它确实允许我拖动它,就好像它正在工作一样,但是通过我的更新函数发送的代码缺少新元素。

//Sort categories
$('#categories-list').find('tbody').sortable({
  connectWith: 'tbody',
  opacity: 0.6,
  cursor: 'move',
  forcePlaceholderSize: true,
  update: function(e) {
    var serialized = $('#categories-list tbody').sortable('serialize');
    console.log(serialized);
    $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
      if (data.status == 'error') {
        alert(data.message);
      }
    });

  }
});


//Add category submit
$("#add-category-submit").click(function(e) {
  e.preventDefault();

  $(".errors-block").html('');

  $('#add-category-submit').hide();

  $.ajax({
    url: $("#add-category-form").attr('action'),
    type: 'POST',
    data: $('#add-category-form').serialize(),
    dataType: 'json',
    success: function(data) {

      $('#add-category-submit').show();

      //Check if server side validation passed
      if (data.status == 'error') {
        //Show error on popup dialog
        $("#add-category-form .errors-block").html(data.message);
        alert('Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.');
      } else {

        var category_data = data.data;

        var tableRow = '<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">&#8597;</span>' +
          '</td><td>' + category_data.title +
          '</td><td></tr>'

        $(tableRow).appendTo('#categories-list tbody');


        resetForm($('#add-category-form'));

        //Close popup window
        $('#add-category').dialog('close');

        $("<div title='Success!'>Category has been saved.</div>").dialog({
          modal: true,
          width: 'auto'
        });

      }

    },
    error: function(data) {
      alert('An unknown error has occurred, please try again.');
      $('#add-category-submit').show();
    }

  });
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>

<table class="data" id="categories-list">
  <thead>
    <tr>
      <th>&nbsp;</th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr id="category-row-19">
      <td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
      <td class="category-row-title">test1</td>
    </tr>
    <tr id="category-row-20">
      <td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
      <td class="category-row-title">test</td>
    </tr>
  </tbody>
</table>

我到处寻找解决方案,但没有找到有效的解决方案。我尝试过将“刷新”功能与可排序一起使用,我尝试在ajax调用的成功函数内初始化可排序以添加新类别,但它也不起作用。

当我 console.log(serialized) 时,它只有数组中最初加载的元素。

最佳答案

不知道发生了什么,但是这个假添加有效,也许你可以模仿这个?请注意,我解决了一些语法问题,并使用 ajax Promise 方法来更好地组织它。

我建议您更新 jQuery 版本,在最新版本中提供一些更好的内容并修复错误。

//Sort categories
$('#categories-list').find('tbody').sortable({
  connectWith: 'tbody',
  opacity: 0.6,
  cursor: 'move',
  forcePlaceholderSize: true,
  update: function(e) {
    var serialized = $('#categories-list tbody').sortable('serialize');
    console.log(serialized);
    //  $.post('admin/ereg_forms/set_category_position', serialized, function(data) {
    //    if (data.status == 'error') {
    //     alert(data.message);
    //  }
    // });
  }
});
$('#addmorefool').on('click', AddMore);

function AddMore() {
  let tbody = $('#categories-list').find('tbody');
  let rowscount = tbody.find('tr').length;
  let newRow = '<tr id="category-row-' + rowscount + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td><td class="category-row-title">test' + rowscount + '</td></tr>';
  tbody.append(newRow);
}

AddMore();


//Add category submit
$("#add-category-sumbit").on('click', function(e) {
  //console.log("howdy");
  e.preventDefault();
  var myform = $("#add-category-form");
  var errorBlock = myform.find(".errors-block");
  errorBlock.html('');
  errorBlock.dialog({
    modal: true,
    width: 'auto',
    autoOpen: false
  });
  var catSub = $('#add-category-submit');
  catSub.hide();

  var myjax = $.ajax({
      url: myform.attr('action'),
      type: 'POST',
      data: myform.serialize(),
      dataType: 'json'
    })
    .done(function(data) {
      catSub.show();
      //Check if server side validation passed
      var category_data = data.data;
      var tableRow = $('<tr class="category-row-' + category_data.id + '"><td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">&#8597;</span>' +
        '</td><td>' + category_data.title +
        '</td><td></tr>');
      let tbody = $('#categories-list').find('tbody');
      tbody.append(tableRow);
      resetForm(myform);
      //Close popup window (out cause have none)
      //('#add-category').dialog('close');
      $("<div title='Success!'>Category has been saved.</div>").dialog({
        modal: true,
        width: 'auto'
      });
    }).fail(function(data) {
      //Show error on popup dialog
      errorBlock.html('<span>Sorry, the information that was sent is invalid. Please review the errors at the top of the form and try again.</span>' + data.message);
      errorBlock.dialog("open");
      //catSub.show(); (out cause not in code)
    });
});
tr td {
  border: 1px solid lime;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div id="add-category-form" action="metoo">I am an empty form, so what
  <div class="errors-block">me error aggain? no way</div>
</div>
<table class="data" id="categories-list">
  <thead>
    <tr>
      <th>&nbsp;</th>
      <th>Title</th>
    </tr>
  </thead>
  <tbody>
    <tr id="category-row-19">
      <td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
      <td class="category-row-title">test1</td>
    </tr>
    <tr id="category-row-20">
      <td><span class="double-arrow-unicode" style="font-size:18px; cursor:pointer;">↕</span></td>
      <td class="category-row-title">test</td>
    </tr>
  </tbody>
</table>

<button id="addmorefool" type="button">Add More</button>
<div class="errors-block">me error</div>
<button type="button" id="add-category-sumbit">add category</button>

关于javascript - jQuery 可排序序列化无法识别动态添加的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882830/

相关文章:

javascript - JQuery如何知道所有失去焦点的选择

javascript - 为什么我无法在我的 Android 应用程序中使用 Cordova 2.7.0 触发 navigator.camera.getPicture?

Javascript JSON stringify 没有要包含在数据中的数字索引

jquery - 日期选择器错误=未捕获类型错误: Cannot read property '0' of undefined

javascript - 使用 jquery 的 addClass 方法覆盖样式表

javascript - JQuery 动态脚本标签和执行

javascript - 如果选择了另一个输入字段,则禁用该输入字段?

javascript - Thymeleaf:使用 Ajax 刷新值

javascript - Rails 4 - 将 Google Maps API JSON 返回值发送到 Controller

javascript - 使用动态填充 ID 值计算 div 的高度