Javascript 度假后获取 jQuery Sortable 列表中列表项的顺序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5320194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:39:09  来源:igfitidea点击:

Get order of list items in a jQuery Sortable list after resort

javascriptjquery

提问by Casey Flynn

I have a list on my website. I'm using jQuery's sortable tutorial to give users the ability to change the order of the list items.

我的网站上有一个列表。我正在使用 jQuery 的可排序教程让用户能够更改列表项的顺序。

http://jqueryui.com/demos/sortable/

http://jqueryui.com/demos/sortable/

The trick is I would like to capture the order of the items immediately after a resort and assign the order values to hidden form elements which would be passed to my server via a form-submit where I could use a php script to save the new order of elements in a database.

诀窍是我想在度假后立即捕获项目的顺序并将订单值分配给隐藏的表单元素,这些元素将通过表单提交传递到我的服务器,我可以在其中使用 php 脚本来保存新订单数据库中的元素。

Here's the source code of the demo:

这是演示的源代码:

 <style>
    #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
    #sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
    #sortable li span { position: absolute; margin-left: -1.3em; }
    </style>
    <script>
    $(function() {
        $( "#sortable" ).sortable();
        $( "#sortable" ).disableSelection();
    });
    </script>


<div class="demo">

<ul id="sortable">
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 6</li>
    <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 7</li>
</ul>

</div><!-- End demo -->

And I'm aware that it's also possible to assign a call-back function that fires when sorting stops:

而且我知道也可以分配一个在排序停止时触发的回调函数:

$( ".selector" ).sortable({
   stop: function(event, ui) { ... }
});

Thanks!

谢谢!

回答by mattsven

I wrote an answer to this question 5 years ago, but that answer sucked (and this question has almost 38,000 views), so here's an improved answer.

我在 5 年前写过这个问题的答案,但那个答案很糟糕(这个问题有近 38,000 次浏览),所以这里有一个改进的答案。

There's essentially three parts of this question that you have to solve. We'll look at all three.

你必须解决这个问题的三个部分。我们将研究所有三个。

Responding to changes in the sort order (Step 1)

响应排序顺序的更改(步骤 1)

The first issue we need to solve is reacting to changes in the order of sorted elements. If we check out the jQuery UI Sortable Widget's documentation, we see that it has a changeevent which fires whenever the sort order changes, and is perfect for our needs.

我们需要解决的第一个问题是对排序元素顺序的变化做出反应。如果我们查看 jQuery UI Sortable Widget 的文档,我们会看到它有一个change事件,它会在排序顺序改变时触发,非常适合我们的需求。

Side note: My original answer used stopinstead of the changeevent. changeis better (at least in this case) because it will report all changes in sorting, whether the change was interactive (user) or programmatic, and only if the order has actually changed. On the other hand, the sortevent is only fired when the user stops sorting (releases the mouse, or lifts their finger).

旁注:我的原始答案用于stop代替change事件。change更好(至少在这种情况下),因为它将报告排序中的所有更改,无论更改是交互式(用户)还是程序化的,并且仅当订单实际发生更改时。另一方面,sort仅当用户停止排序(释放鼠标或抬起手指)时才会触发该事件。

Using the sortevent, we can now respond to changes in sorting. The following will initialize a Sortablewidget for us, and allow us to set a function to be called when the sorteven fires:

使用该sort事件,我们现在可以响应排序的变化。下面将为Sortable我们初始化一个小部件,并允许我们设置一个函数,以便在sort偶数触发时调用:

var $sortableList = $("#your-list");

var sortEventHandler = function(event, ui){
    console.log("New sort order!");
};

$sortableList.sortable({
    stop: sortEventHandler
});

// You can also set the event handler on an already existing Sortable widget this way:

$sortableList.on("sortchange", sortEventHandler);

With that done, we're now ready to take on step 2:

完成后,我们现在准备进行第 2 步:

Retrieving the sorted elements (Step 2)

检索已排序的元素(步骤 2)

This part is fairly simple. We just need to get an array of the elements in our sorted list. To do this, we can just ask for the children of the ul(list) element, using the jQuery function children():

这部分相当简单。我们只需要获取排序列表中的元素数组。为此,我们可以ul使用 jQuery 函数请求(list) 元素的子元素children()

var listElements = $sortableList.children();

console.log(listElements); // [ <li>, <li>, ... ]

Great, but we specifically need the element's values:

很好,但我们特别需要元素的值:

var listValues = [];

listElement.forEach(function(element){
    listValues.push(element.innerHTML);
});

console.log(listValues); // [ "Item 1", "Item 2", ... ]

Using .sortable("toArray")or .serialize()are also options.

使用.sortable("toArray").serialize()也是选项。

Nice! On to the final bit.

好的!到最后一点。

Serializing & sending off the new sorted order (Step 3)

序列化并发送新的排序顺序(步骤 3)

Serialization is "the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link)" (thanks Wikipedia!)

序列化是“将数据结构或对象状态转换为可以存储的格式的过程(例如,在文件或内存缓冲区中,或通过网络连接链接传输)”(感谢维基百科!)

How you do this depends a lot on your specific needs, so we'll just discuss some of the ways you could get it done using jQuery.

您如何做到这一点在很大程度上取决于您的特定需求,因此我们将仅讨论您可以使用 jQuery 完成它的一些方法。

AJAX:

阿贾克斯:

If we use AJAX, we can just shoot off a request to the server with the new order. jQuery will automatically handle serializing listValuesfor us:

如果我们使用 AJAX,我们可以使用新订单向服务器发送请求。jQuery 会自动listValues为我们处理序列化:

$.post("your-server.com/save_order", { "items": listValues } );

Or if you prefer JSON:

或者,如果您更喜欢 JSON:

$.post("your-server.com/save_order", JSON.encode({ "items": listValues }) );

Form

形式

Create a form:

创建表格:

<form action="your-server.com/save_order" method="POST">
    <input name="items" value="" />
</form>

Update the iteminput:

更新item输入:

var serializedValue = $.param(listValues);

$("#ourForm > input").val(JSON.encode(listValues));

Send it:

发送:

$("#ourForm").submit()

Old answer:

旧答案:

HTML:

HTML:

<form action="save_order.php" method="POST" style="display: none;">
<input name="new_order" value="" type="hidden" />
</form>

JavaScript:

JavaScript:

$(".selector").sortable({
    stop: function(event, ui) {
        var data = "";

        $("#sortable li").each(function(i, el){
            var p = $(el).text().toLowerCase().replace(" ", "_");
            data += p+"="+$(el).index()+",";
        });

        $("form > [name='new_order']").val(data.slice(0, -1));
        $("form").submit();
    }
});

And in save_order.php, you can parse the POST variable "new_order" and get the orders of Item 1, Item 2, Item 3, etc.

而在save_order.php中,可以解析POST变量“new_order”,获取Item 1、Item 2、Item 3等的订单。

回答by Kyle

Try using serializeto format a string to send to your database update script.

尝试使用serialize格式化字符串以发送到您的数据库更新脚本。

http://jsfiddle.net/zFQ2j/

http://jsfiddle.net/zFQ2j/

http://docs.jquery.com/UI/Sortable#method-serialize

http://docs.jquery.com/UI/Sortable#method-serialize

回答by FabriGad Ahmed

May this helps:

这可能会有所帮助:

alert($( "#sortable" ).sortable( "toArray" ).toSource());

回答by Gediminas

May, 2018

2018 年 5 月

This Javascript example will give you all list of DIVS in #sortableContainer each time sorting is done

每次排序完成时,此 Javascript 示例将为您提供 #sortableContainer 中的所有 DIVS 列表

<div id="sortableContainer">
   <div id="Element1" class="sortIt">Item 1</div>
   <div id="Element2" class="sortIt">Item 2</div>
   <div id="Element3" class="sortIt">Item 3</div>
   <div id="Element4" class="sortIt">Item 4</div>
</div>

JS:

JS:

$( function() {
  $( "#sortableContainer" ).sortable({

    stop: function(event, ui) {

      var itemOrder = $('#sortableContainer').sortable("toArray");

      for (var i = 0; i < itemOrder.length; i++) {
        console.log("Position: " + i + " ID: " + itemOrder[i]);
      }

    }
  });

});

DEMO and Credits: http://www.tutorialspark.com/jqueryUI/jQuery_UI_Sortable_Getting_Order_of_Sortable.php

演示和积分:http: //www.tutorialspark.com/jqueryUI/jQuery_UI_Sortable_Getting_Order_of_Sortable.php

回答by Ramas Win

Easy to solve:

轻松解决:

jQuery_2( function() {
 var url = '<?php echo base_url(); ?>planner/Planner/edit_status/';
 jQuery_2('ul[id^="sort"]').sortable({
     connectWith: ".sortable",
     /*receive: function (e, ui) {
         var status_id = jQuery_2(ui.item).parent(".sortable").data("status-id");
         var task_id = jQuery_2(ui.item).data("task-id");
         jQuery_2.ajax({
             url: url,
             method: 'POST',
             data: { status_id: status_id, task_id: task_id, },
             success: function(response){ }
         });
    },*/
    update: function(e, ui) {
        var status_id = jQuery_2(ui.item).parent(".sortable").data("status-id");
        var task_id = jQuery_2(ui.item).data("task-id");
        var order_id = jQuery_2(ui.item).index();
        jQuery_2.ajax({
            url: url,
            method: 'POST',
            data: { status_id: status_id, task_id: task_id, order_id: order_id, },
            success: function(response){ }
        });
    }

 }).disableSelection();
 } );

var order_id = jQuery_2(ui.item).index(); // Get order

var order_id = jQuery_2(ui.item).index(); // 获取订单

回答by Ramas Win

And you can:

你可以:

jQuery_2( function() {
 var url = '<?php echo base_url(); ?>planner/Planner/edit_status/';
 jQuery_2('ul[id^="sort"]').sortable({
     connectWith: ".sortable",
     /*receive: function (e, ui) {
         var status_id = jQuery_2(ui.item).parent(".sortable").data("status-id");
         var task_id = jQuery_2(ui.item).data("task-id");
         jQuery_2.ajax({
             url: url,
             method: 'POST',
             data: { status_id: status_id, task_id: task_id, },
             success: function(response){ }
         });
    },*/
    update: function(e, ui) {
        var status_id = jQuery_2(ui.item).parent(".sortable").data("status-id");
        var task_id = jQuery_2(ui.item).data("task-id");
        //var order_id = jQuery_2(ui.item).index();
        var order_id = [];

        $("#sort"+status_id+" li").each(function(index) {
            order_id.push($(this).attr('data-task-id'));
        });

        jQuery_2.ajax({
            url: url,
            method: 'POST',
            data: { status_id: status_id, task_id: task_id, order_id: order_id, },
            success: function(response){ }
        });
    }

 }).disableSelection();
 } );

回答by user1495495

This is how i did that Use event handler to capture the sort event and then get the sorted values through ToArray function and loop through the values and assign to array. This array then you can pass to Ajax post

这就是我这样做的方式 使用事件处理程序捕获排序事件,然后通过 ToArray 函数获取排序后的值并循环遍历这些值并分配给数组。这个数组然后你可以传递给 Ajax 帖子

    var $sortableList = $("#sortable");

var sortEventHandler = function(event, ui){
    var sortedIDs = $( "#sortable" ).sortable( "toArray" );
                var listValues = [];
                for (var i = 0; i < sortedIDs.length; i++) {

                listValues.push(sortedIDs[i]);
      }
            console.log(listValues);
};

$sortableList.sortable({
    stop: sortEventHandler
});

$sortableList.on("sortchange", sortEventHandler);