【问题标题】:Detect if element position was changed in Jquery UI sortable检测元素位置是否在 Jquery UI 可排序中发生了变化
【发布时间】:2013-05-29 10:49:23
【问题描述】:

我使用以下代码在我的网站上重新订购商品:

$(document).ready(function () {
    $("#my-list").sortable({
        stop: function (event, ui) {
            var id = $(ui.item).attr('id');

            var url = '/en/account/changeposition?id=idreplace&position=posReplace';

            url = url.replace("idreplace", id);
            url = url.replace("posReplace", ui.item.index());

            window.location.href = url;
        },
        distance: 15
    });
});

但是,即使我不改变元素位置并将元素放置在同一个地方,Jquery UI 也会调用'stop'-function。

是否可以在不使用自定义数据属性的情况下检测元素索引(位置)是否已更改?

// I would like to avoid adding custom data attributes like this:
<li id="id100" data-original-position="1"></li>
<li id="id101" data-original-position="2"></li>

【问题讨论】:

    标签: jquery jquery-ui


    【解决方案1】:

    创建一个布尔值

    sortableChanged = false;
    

    JQuery可排序的更新中设置为true

    【讨论】:

      【解决方案2】:

      虽然在大多数情况下使用更新事件似乎是最佳答案,但值得注意的是,如果元素没有移动,则不会触发此事件。

      虽然这在大多数情况下可能没问题,但您可能需要在可排序停止但未进行任何更改时运行一些代码(我发现自己需要重置一些全局变量)。这只有使用接受的答案才有可能。

      【讨论】:

        【解决方案3】:

        http://api.jqueryui.com/sortable/#event-update得到这个

        update( event, ui )类型:sortupdate 当用户停止排序且 DOM 位置发生变化时触发该事件

        据此,更新是您唯一需要的...因为更新会检测 DOM 位置是否已更改。

        【讨论】:

          【解决方案4】:

          除非我遗漏了什么,否则update 事件将是您最好的选择。根据documentation

          当用户停止排序并且DOM位置发生变化时触发该事件。

          因此,如果您在用户停止拖动时唯一关心的是索引是否更改,则只需使用update 即可省去设置和评估数据属性的麻烦。

          【讨论】:

          • 我同意,我只需要更新部分。排序完成后,我只需使用与容器 &lt;div&gt; 关联的 id="xxx" 字段序列化数组并更新数据库中的字段。
          【解决方案5】:

          看看this answer

          它对我的工作如下:

          $(selector).sortable({
              start: function(event, ui) {
                  ui.item.data('start_pos', ui.item.index());
              },
              stop: function(event, ui) {
                  var start_pos = ui.item.data('start_pos');
                  if (start_pos != ui.item.index()) {
                      // the item got moved
                  } else {
                      // the item was returned to the same position
                  }
              },
              update: function(event, ui) {
                  $.post('/reorder', $(selector).sortable('serialize'))
                      .done(function() {
                          alert('Updated')
                      });
                  }
          });
          

          【讨论】:

            猜你喜欢
            • 2014-05-30
            • 1970-01-01
            • 1970-01-01
            • 2011-02-28
            • 2012-06-13
            • 2015-09-26
            • 2013-10-28
            • 2012-08-18
            • 1970-01-01
            相关资源
            最近更新 更多