使用getJSON方法的Jquery Sortable List

时间:2014-01-08 16:01:54

标签: javascript jquery-ui getjson

我正在开发一个使用getJSON将列表项添加到DOM的教程。还需要JqueryUI可排序插件来对列表进行排序。由于某些原因我不知道该插件不起作用。我在这里错过了什么?可排序函数应该在getJSON回调中吗?任何建议都会很棒。

这是我到目前为止的代码:

$(function () {
 $('body h1').append('My Todo List');

 $.getJSON('todo.json', function(data) {

var html = '<ul id="sortable" class="ui-sortable">';

$.each(data, function(index) {

    var todo = data[index];
    if (todo.done === false) {
        todo.done = (" ")

    } else {
        todo.done = ("(DONE)")
    }
    html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
    html += '</ul>';
   $('body #container').append(html);
});



});

HTML文件:

<!DOCTYPE html>
<html>
<head>
    <title>Jquery ToDo List</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="todo.js"></script>
    <script>
        $(function () {
            $("#sortable").sortable("refresh");
            $("#sortable").disableSelection("refresh");
        });
    </script>
    <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: 14px; height: 18px; }
        #sortable li span { position: absolute; margin-left: -1.3em; }
    </style>
</head>
<body>
<h1></h1>
<div id="container">

</div>



</body>
</html>

JSON

[
{"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
{"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
{"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
{"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}

1 个答案:

答案 0 :(得分:0)

你必须在追加数据后调用sortable。在$.getJSON回调中再次致电sortable,如下所示。只有在dom准备就绪时sortable中存在元素时,jquery才会连接DOM。您是动态添加元素,因此在将元素添加到sortable后,您必须再次调用DOM

 $.getJSON('todo.json', function(data) {

var html = '<ul id="sortable" class="ui-sortable">';

$.each(data, function(index) {

    var todo = data[index];
    if (todo.done === false) {
        todo.done = (" ")

    } else {
        todo.done = ("(DONE)")
    }
    html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
    html += '</ul>';
   $('body #container').append(html);
});

$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();

});

修改

这是bin http://jsbin.com/IPubElE/1/

demo使用内存中的数据,但即使在回调方法中也应该可以正常工作。