繁体   English   中英

使用getJSON方法的jQuery可排序列表

[英]Jquery Sortable List with getJSON method

我正在研究使用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}

]

您必须在添加数据后调用sortable $.getJSON回调中,再次调用sortable ,如下所示。 当dom准备就绪时,仅当DOM包含元素时,jquery才会连线sortable 您正在动态添加元素,因此在将元素添加到DOM之后必须再次调用sortable

 $.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/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM