javascript 使用 jQuery UI 可排序插件添加项目后刷新列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22560724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:22:03  来源:igfitidea点击:

Refresh list after adding an item with jQuery UI sortable plugin

javascriptjqueryhtmlcssjquery-ui

提问by Warrior

Alright so I have a nested sortable list, each item is therefore both a container and a sortable element.

好的,所以我有一个嵌套的可排序列表,因此每个项目既是容器又是可排序元素。

The problem I am facing is that, whenever I add a new element, I want jQuery to refresh its internal state with the new item. According to the documentation, one has to call the sortable method passing as parameter 'refresh', but still I can't make it work.

我面临的问题是,每当我添加一个新元素时,我都希望 jQuery 用新项目刷新其内部状态。根据文档,必须调用作为参数“刷新”传递的可排序方法,但我仍然无法使其工作。

Sample code: http://jsfiddle.net/X5sBm/

示例代码:http: //jsfiddle.net/X5sBm/

JavaScript:

JavaScript:

$(document).ready(function() {
    var list = $('#mycontainer ul').sortable({
        connectWith: '#mycontainer ul',
        placeholder: 'myplaceholder'
    });

    function addElement(text) {
        $('#mycontainer > ul').append('<li>' + text + '<ul></ul></li>');
        list.sortable('refresh');
    }

    addElement('yolo');
});

HTML:

HTML:

<div id="mycontainer">
    <ul>
        <li>
            Some text
            <ul>
            </ul>
        </li>
        <li>
            Some text 2
            <ul>
            </ul>
        </li>
    </ul>
</div>

CSS:

CSS:

#mycontainer > ul {
    display: block;
}

#mycontainer > ul ul {
    min-height: 10px;
    padding-left: 20px;
}

.myplaceholder {
    background-color: yellow;
}

Try to drag one pre existing item under the newly added one, you won't be able to do so even after the refresh.

尝试将一个预先存在的项目拖到新添加的项目下,即使刷新后您也无法这样做。

回答by Warrior

I found a cheap fix:

我找到了一个便宜的解决方案:

I call sortable again on the same tag reinitialising the Sortable plugin like so:

我在同一个标​​签上再次调用 sortable 重新初始化 Sortable 插件,如下所示:

$('#mycontainer ul').sortable({
    connectWith: '#mycontainer ul',
    placeholder: 'myplaceholder'
});

and it works.

它有效。