使用 sortable jquery 检查 div 中图像的顺序

Check the order of images inside div using sortable jquery

所以我在 div 中有图像,我在 jquery 上使用可排序插件来拖放图像的排列。我只需要弄清楚图像的编号排列,即使我拖放它也是如此。 例如,我将 test2.jpg 拖到 test1.jpg 前面。所以排列应该是1. test2.jpg, 2. test1.jpg, 3. test3.jpg.

html

<div id="sortable">
    <img id="product_preview" class="ui-state-default" src="/images/test1.jpg">
    <img id="product_preview" class="ui-state-default" src="/images/test2.jpg">
    <img id="product_preview" class="ui-state-default" src="/images/test3.jpg">
<div>

javascript

$( function() {
   $( "#sortable" ).sortable();
   $( "#sortable" ).disableSelection();
} );

您需要使用 serializetoArray 来收集此详细信息。您需要确保每件商品的 ID 都是正确的。

Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2". You can use an underscore, equal sign or hyphen to separate the set and number. For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".

$(function() {
  $("#sortable").sortable({
    update: function(event, ui) {
      var sorted = $(this).sortable("serialize");
      var sortedIDs = $(this).sortable("toArray");
      console.log(sorted, sortedIDs);
    }
  });
  $("#sortable").disableSelection();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="sortable">
  <img id="product_1" class="ui-state-default" src="/images/test1.jpg" />
  <img id="product_2" class="ui-state-default" src="/images/test2.jpg" />
  <img id="product_3" class="ui-state-default" src="/images/test3.jpg" />
<div>

查看更多: