如何在JQuery中的可拖动元素的上下文中注入对象?

时间:2009-09-16 18:40:49

标签: jquery drag-and-drop draggable droppable

我使用draggable / droppable JQuery功能如下

div.container {
    height:400px;
}

<div class="container" id="source">
    <div id="0">Item 0</div>
    <div id="1">Item 1</div>
    <div id="2">Item 2</div>
</div>

<div class="container" id="target"></div>

$("#source div").draggable({
    helper:"clone",
        revert:"invalid"
    });

我想知道是否可以在可拖动对象的上下文中注入对象。像

这样的东西
var contextualObject = {"property":"value"};

$("#source div").draggable({
    helper:"clone",
        revert:"invalid",
        injected:contextualObject
    });

所以在目标容器中我可以使用类似的东西(通知第二个警告声明)

$("#target").droppable({
    accept:"#source div",
tolerance: "fit",
drop:function(e, ui) {
        alert("You have dropped id " + $(this).attr("id"));

        alert("Its contextual value is: " + $(this).draggable("option", "injected.property"));
}});

我该怎么做?

的问候,

1 个答案:

答案 0 :(得分:2)

jQuery data就是出于这种情况。

$("#source div").draggable({
    helper:"clone",
        revert:"invalid",
        start: function(evt,ui) {
           $(this).data('injected', contextualObject)
        }
    });

然后,在你的droppable中:

 var obj = $(ui.draggable).data('injected');
 console.log(obj.property);

几点说明:

  • 您应该在放置中使用ui.draggable来获取拖放项目。 this是被放弃的项目
  • 元素ID应该从with a letter开始,而不是数字。

我有一个有效的演示here