【问题标题】:jQuery UI: Dynamically add elements to sortablejQuery UI:动态添加元素到可排序
【发布时间】:2014-02-18 22:59:07
【问题描述】:

我正在动态构建一个可排序列表,但是当动态添加元素时,可排序开始表现不正确:

function buildHTML() {
    var selection = ['number', 'items', 'list'];
    var component = $('#selector');
    component.empty();

    for (var i = 0; i < selection.length; i++) {
        component.append('<li class="drag-button"> ' + selection[i] + '</li>');
    }

    component.sortable('refresh');
}

$('#selector').sortable({ 
    tolerance: 'pointer',
    cursor: 'move',
    axis: 'x'
});

buildHTML(); 

通常在缓慢拖动时,被拖动的项目将能够越过另一个项目而不会移动到空白位置。

可以在此处找到示例:http://jsfiddle.net/LRkg4/

在拖动项目“数字”时,它通常能够越过项目“列表”,而“列表”不会向左移动。感觉完全不同于静态版本:http://jsfiddle.net/cbXK3/1/,我首先构建 HTML,然后创建可排序:

buildHTML();
$('#selector').sortable({...});

【问题讨论】:

    标签: javascript jquery jquery-ui jquery-ui-sortable


    【解决方案1】:

    这很奇怪。查看两者之间的来源看起来相同。一定是 jQuery 引擎盖下的一些不正确的东西。

    这可能不是您正在寻找的答案,但它确实有效,项目排序非常快捷。一个简单的销毁,添加您的动态项目,然后重建:http://jsfiddle.net/BzfY3/3/(请参阅小提琴)

    <ul id="selector">
        <li class="drag-button">some</li>
        <li class="drag-button">inital</li>
        <li class="drag-button">stuff</li>
    </ul>
    <br/><br/><br/><br/>
    <input type="button" value="Add some sortable items and rebuild it" onclick="reBuildIt()">
    
    <script>
    //this function will destroy, add your new items, then rebuild it
    window.reBuildIt=function() {
        var selection = ['number', 'items', 'list'];
        var component = $('#selector');
        component.sortable('destroy');
    
        for (var i = 0; i < selection.length; i++) {
            component.append('<li class="drag-button"> ' +
            selection[i] + 
            '</li>');
        }
    
        $('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' }); 
    }
    
    //show any initial sortable items
    $('#selector').sortable({ tolerance: 'pointer', cursor: 'move', axis: 'x' });
    </script>
    

    【讨论】:

    • 发现和空的
        有关。当我在 HTML 中添加一个
      • 时,它似乎可以正常工作。所以可能 sortable 在初始化时缓存了一些变量,并且在刷新时不会更新这些变量! jsfiddle.net/p88Hf/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2014-02-17
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 2014-05-12
    相关资源
    最近更新 更多