为可放置项添加唯一ID

时间:2012-10-02 16:26:08

标签: jquery draggable unique droppable unique-id

我有一个小部件,我可以将物品放入垃圾桶。我希望能够在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>

1 个答案:

答案 0 :(得分:5)

您可以使用类似日期对象

创建唯一ID
var uniqueId = new Date().getTime();

要获取列表项的名称,您可以在放置事件

中访问它
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 );
    }
});