2

我有一个小部件,我可以在其中将物品放入垃圾桶。我希望能够在 drop 事件中为丢弃在垃圾桶中的每个项目添加一个唯一的 ID。我该怎么做?有没有办法让输出值成为列表项的实际名称?谢谢!下面是我的代码:

    $(function() {
    var $gallery = $( "#gallery" ),
        $trash = $( "#trash" );


    $( "li", $gallery ).draggable({
        cancel: "a.ui-icon", 
        revert: "invalid", 
        containment: $( "#demo-frame" ).length ? "#demo-frame" : "document", // stick to demo-frame if present
        helper: "clone",
        cursor: "move"
    });


    $trash.droppable({
        accept: "#gallery > li",
        activeClass: "ui-state-highlight",
        drop: function( event, ui ) {
            deleteImage( ui.draggable );
        }
    });

    $gallery.droppable({
        accept: "#trash li",
        activeClass: "custom-state-active",
        drop: function( event, ui ) {
            recycleImage( ui.draggable );
        }
    });

HTML

 <div class="demo ui-widget ui-helper-clearfix">

<ul id="gallery" class="gallery ui-helper-reset ui-helper-clearfix">
    <li class="ui-widget-content ui-corner-tr" a href="link/to/trash/script/when/we/have/js/off">
        <h5 class="fpheader">Red</h5>   

    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Orange</h5>

    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader"Yellow</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Green</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheaderr">Blue</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">Purple</h5>
    </li>
    <li class="ui-widget-content ui-corner-tr">
        <h5 class="fpheader">White</h5>

    </li>
</ul>

</div>
4

1 回答 1

6

您可以使用这样的日期对象创建唯一 ID

var uniqueId = new Date().getTime();

要获取列表项的名称,可以在 drop 事件中访问

var listNameId = ui.draggable.children('.fpheader').text().toLowerCase();

您可以从 UI 对象访问克隆的项目

ui.helper

您可以从 UI 对象访问原始项目

ui.draggable

下面的示例为克隆的项目添加一个唯一 ID

$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        // unique ID based on ID
        var uniqueId = new Date().getTime();
        // set unique ID to cloned list item
        ui.helper.attr('id', uniqueId);
        deleteImage( ui.draggable );
    }
});

下面的示例将列表名称添加到原始项目

$trash.droppable({
    accept: "#gallery > li",
    activeClass: "ui-state-highlight",
    drop: function( event, ui ) {
        // list item text, i.e "white"
        var listNameId = ui.draggable.children('.fpheader').text().toLowerCase();
        // set list name ID to orriginal list item
        ui.draggable.attr('id', listNameId);
        deleteImage( ui.draggable );
    }
});
于 2012-10-02T17:18:36.020 回答