在度假后获取jQuery可排序列表中的列表项的顺序 [英] Get order of list items in a jQuery Sortable list after resort

查看:73
本文介绍了在度假后获取jQuery可排序列表中的列表项的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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.

以下是演示的源代码:

 <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) { ... }
});

谢谢!

推荐答案

5年前我写了这个问题的答案,但答案很糟糕(这个问题有近38,000个观点),所以这里有一个改进的答案。

这个问题基本上有三个部分需要解决。我们将查看所有三个。

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

我们需要解决的第一个问题是对排序元素顺序的变化作出反应。如果我们查看jQuery UI可排序窗口小部件的文档,我们会看到它有 更改 事件,当排序顺序发生变化时会触发该事件,并且非常适合我们的需求。

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 change event which fires whenever the sort order changes, and is perfect for our needs.


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

Side note: My original answer used stop instead of the change event. change is 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 sort event is only fired when the user stops sorting (releases the mouse, or lifts their finger).

使用 sort 事件,我们现在可以响应排序中的更改。以下将为我们初始化一个 Sortable 小部件,并允许我们设置一个在 sort 时调用的函数fires:

Using the sort event, we can now respond to changes in sorting. The following will initialize a Sortable widget for us, and allow us to set a function to be called when the sort even fires:

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);

完成后,我们现在准备采取第2步:

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

这部分非常简单。我们只需要在排序列表中获取元素数组。为此,我们可以使用jQuery函数 children() ul (list)元素的子元素。 c>:

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():

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", ... ]

使用 .sortable(toArray) .serialize() 还有选择。

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

很好!到最后一点。

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

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!)

你如何做到这一点很大程度上取决于你的具体需求,所以我们将讨论一些你可以用jQuery完成它的方法。

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.

AJAX:

如果我们使用AJAX,我们可以用新的方式向服务器发出请求订购。 jQuery将自动为我们处理序列化 listValues

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

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

或者如果您更喜欢JSON:

Or if you prefer JSON:

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

表格

创建表单:

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

更新项目输入:

var serializedValue = $.param(listValues);

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

发送:

$("#ourForm").submit()



旧答案:



HTML:

Old answer:

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();
    }
});

在save_order.php中,您可以解析POST变量new_order并获取Item的订单1,第2项,第3项等

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.

这篇关于在度假后获取jQuery可排序列表中的列表项的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆