将订单设置为可排序的jQuery [英] set order to jquery sortable
问题描述
我将jquery draggble函数用于无序列表(ul),并遇到在更改项目并加载页面设置顺序后获取项目顺序的问题.假设我们有以下代码:
I use jquery draggble function for unorderd list (ul) and face a problem of getting the order of items after it changed and setting the order ofter page is loaded.Suppose we have the following code :
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$('.secondblock').sortable({axis:'y'});
$(".block").sortable({
axis: 'y',
update: function(event, ui) {// order changed
var order = jQuery(this).sortable('toArray');
// set this order to .secondblock
}
});
});
</script>
</head>
<body>
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
</body>
有没有可能的解决方案?
Are there any possible solutions?
推荐答案
首先,您不应让同一id在文档中出现两次.那会引起各种各样的问题.
First, you shouldn't have the same id appear twice in a document. That will cause all kinds of problems.
相反,在第二个列表中的项目上设置数据属性以反映第一个列表中的相应项目:
Instead, set a data-attribute on the items in the second list to reflect corresponding items in the first list:
<ul class="block" type="none">
<li id = "one">1</li>
<li id = "two">2</li>
<li id = "three">3</li>
<li id = "four">4</li>
<li id = "five">5</li>
</ul>
<ul class="secondblock" type="none">
<li data-block-id = "one">1</li>
<li data-block-id = "two">2</li>
<li data-block-id = "three">3</li>
<li data-block-id = "four">4</li>
<li data-block-id = "five">5</li>
</ul>
然后在第二个列表中反映第一个列表的类型很简单:
Then reflecting the sort of the first list in the second list is simple:
$('.block').sortable({update: sortOtherList});
function sortOtherList(){
$('.block li').each(function(){
$('.secondblock [data-block-id=' + $(this).attr('id') + ']')
.remove()
.appendTo($('.secondblock'));
});
}
在此处查看其工作方式: http://jsfiddle.net/6HKZG/2/
See it working here: http://jsfiddle.net/6HKZG/2/
这篇关于将订单设置为可排序的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!