以预定义的顺序初始化“jQuery UI可排序列表”

前端之家收集整理的这篇文章主要介绍了以预定义的顺序初始化“jQuery UI可排序列表”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用jQuery UI排序的列表.第一个列表项是“项目1”,第二个是“项目2”.我的要求是必须根据存储在数组“arrValuesForOrder”中的顺序初始化列表项.我们如何初始化它呢?
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js"></script>

<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.13/themes/sunny/jquery-ui.css"
rel="stylesheet" type="text/css" />

<script type="text/javascript">


    $(document).ready(function () 
    {

        var arrValuesForOrder = ["3","1","4","2"];

        $("#myUnorderedList").sortable({
                                    axis:'y',handle: '.handle',update: function () 
                                            {
                                                var order = $('#myUnorderedList').sortable('serialize');
                                                alert(order);
                                            }
        });
    }); 
</script>

<style>

#myUnorderedList li img.handle 
{
margin-right: 20px;
cursor: move;
}

#myUnorderedList li 
{
display: block;
margin-bottom: 3px;
height:30px;
background-color: #efefef;
}

</style>


</head>

<body>

<div>


<ul id="myUnorderedList"> 

  <li id="listItem_1"> 
    <img src="images/arrow.png" alt="move"  class="handle" /> 
    <strong>Item 1</strong> 
  </li> 

  <li id="listItem_2"> 
    <img src="images/arrow.png" alt="move" class="handle" /> 
    <strong>Item 2</strong> 
  </li> 

  <li id="listItem_3"> 
    <img src="images/arrow.png" alt="move"  class="handle" /> 
    <strong>Item 3</strong> 
 </li> 

  <li id="listItem_4"> 
    <img src="images/arrow.png" alt="move" class="handle" /> 
    <strong>Item 4</strong> 
  </li> 

</ul> 


</div>

</body>
</html>

解决方法

我不认为可排序插件附带一个选项来设置元素的初始顺序.我认为它希望元素最初以正确的顺序呈现(在我看来这是有道理的 – 你为什么不那样做?)

无论如何,这里是一段代码,它将在初始化可排序插件之前对元素进行排序:

var arrValuesForOrder = ["3","2"];

var $ul = $("#myUnorderedList"),$items = $("#myUnorderedList").children();

// loop backwards so you can just prepend elements in the list
// instead of trying to place them at a specific position
for (var i = arrValuesForOrder[arrValuesForOrder.length - 1]; i >= 0; i--) {
    // index is zero-based to you have to remove one from the values in your array
    $ul.prepend( $items.get(arrValuesForOrder[i] - 1));
}

$("#myUnorderedList").sortable({
    axis: 'y',update: function() {
        var order = $('#myUnorderedList').sortable('serialize');
        alert(order);
    }
});

DEMO

原文链接:https://www.f2er.com/jquery/180929.html

猜你在找的jQuery相关文章