我想写一个重新排序的用户界面?怎么做


<ul style="padding: 5px; margin-left: 20px;">
Hardware
<li style="padding: 10px; margin-left: 40px;">Product 1</li>
<li style="padding: 10px; margin-left: 40px;">Product 2</li>
<li style="padding: 10px; margin-left: 40px;">Product 3</li>
<li style="padding: 10px; margin-left: 40px;">Product 4</li>
<li style="padding: 10px; margin-left: 40px;">Product 5</li>
</ul>

I have this structure i want to do a reodering interface where user can move product 5 up in the hiearchy by click up arrow and likewise bring something down. I want to do this using javascript of jQuery. I just need some hint about how to do it right.

demo here: http://jsfiddle.net/ruisoftware/ECpfK/

This code should help you get started:

var $moveProduct = $("li").eq(4); // product5
$("#up").click(function() {
    $moveProduct.prev().before($moveProduct);
});
$("#down").click(function() {
    $moveProduct.next().after($moveProduct);
});

它使产物上下移动。

我简化了你的标记,通过移动内联css到一个分离的样式表。

如果您正在使用jQuery,您可能需要考虑jQuery- ui。

这是非常简单的建立自己的,但现有的有真正的抛光:http://jqueryui.com/demos/draggable/#sortable

基本上有两件事需要解决。您必须使这些DOM元素移动,并且必须找到一种方法来收集输入元素中的当前订单(以便能够将其发送到服务器)。

移动元素非常容易使用jQuery的魔法函数。@Jose给了你一个简单但有效的例子。

我建议您将产品的id保存在data-属性中,因为这样更容易处理。您将需要一个方法来收集当前设置的订单中的id,并将它们保存在逗号分隔的字符串中(每当订单更改时,都必须调用此方法)。你可以发送到服务器

用这样的标记:

<ol class="orderable-list">
    <li data-id="24">Terrific Product</li>
    <li data-id="32">Amazing Product</li>
    <li data-id="11">Must-buy Product</li>
<ol>
<input type="hidden" id="current-order" />

您可以使用.map()轻松地收集当前订单并将其保存到输入:

var order = $('.orderable-list li').map(function () {
    return $(this).data('id');
}).get();
$('#current-order').val(order.join(','));

请查看这个jsFiddle演示

最新更新