javascript - 在 draggable 中放置新对象

标签 javascript jquery

如何附加 data-mine 的值? (下降后)

THE DEMO

这是我的房间

jQuery

$(function() {
    var transferred = false;
    $('#draggable li').draggable({
        connectToSortable: '#sortable',
        helper: 'clone',
    });

    $('#sortable').sortable();
});

HTML

<ul id="draggable">
    <li data-mine='hi'>Hello</li>
    <li data-mine='why'>Stack</li>
    <li data-mine='flow'>Overflow</li>
</ul>


<ul id="sortable"></ul>

最佳答案

您需要为 .draggable() 使用 jQuery UI 才能工作,因为常规 jQuery 没有 .draggable()。只要确保你包含它,一切都会正常工作。

此外,要获取原始列表中的data-mine 属性,请在receive 事件中使用ui.item,然后使用.attr() 并将其保存在变量中。然后,要在新列表中附加 data-mine 属性,请在 stop 事件中使用 ui.item,然后使用 。 text() 与前面提到的变量。

$(function() {
    var transferred = false;
    $('#draggable li').draggable({
        connectToSortable: '#sortable',
        helper: 'clone',
    });

    var sortable = $('#sortable');
    //This is the data-mine attribute of the last object dropped in:
    var curDataMine;
    sortable.sortable({
        receive: function(event, ui) {
            transferred = true;
            //Here, we append the data-mine attribute onto the item in the original list:
            curDataMine = ui.item.attr("data-mine");
        },
        stop: function(event, ui)
        {
            transferred = true;
            //Here, we append the data-item attribute onto the item in the sortable list:
            ui.item.text(curDataMine);
        }
    });
});
#draggable, #sortable {
    float: left;
    width: 100px;
    margin: 30px;
}

#draggable li, #sortable li {
    margin-top: 5px;
    background-color: #aaa;
}
#sortable {
    border: 1px solid red;
    width:100px;
    height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<ul id="draggable">
    <li data-mine='hi'>Hello</li>
    <li data-mine='why'>Stack</li>
    <li data-mine='flow'>Overflow</li>
</ul>


<ul id="sortable"></ul>

关于javascript - 在 draggable 中放置新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32157220/

相关文章:

javascript - 如何使用 jQuery/Javascript 运行浏览器命令?

javascript - 计算产品数量和选项附加税的JS函数

javascript - 继承时原型(prototype)方法中的“this”未按预期解析

javascript - Vue.js 组件彼此不独立

javascript - 为什么 React/Redux 会重置所有事件处理程序,即使 `state` 没有改变

javascript - 纯 javascript 的触发器类不起作用

javascript - React 加载 Spinner + Redux?

javascript - 如何替换 Dojo 中的 div?每次点击都会重复显示 div

jquery - 使用 java 在不同屏幕尺寸之间更改导航菜单 HTML?

javascript - 函数之前的 jQuery 选择器