使用jquery draggable / droppable在drop上设置变量

时间:2009-02-05 18:12:48

标签: javascript jquery jquery-ui

我正在研究使用jquery ui draggable / droppable的概念证明。

我正在寻找一种方法来设置一个变量,该变量等于放入droppable区域的div的索引。 (假设我有名为“div0”,“div1”,“div2”等的div ...)

所以想象代码看起来像这样:

<div id="div0" class="draggableDiv">some cotent</div>
<div id="div1" class="draggableDiv">more content</div>
<div id="div2" class="draggableDiv">yet more content</div>

<div class="droppableDiv">drop it here</div>

$(document).ready(function() {
    $('.draggableDiv').draggable({helper: 'clone'});
    $('.droppableDiv').droppable({
        accept: '.draggableRecipe',
        drop: function(ev, ui) { 
            ui.draggable.clone().fadeOut("fast", 
            function() { 
                $(this).fadeIn("fast") 
            }).appendTo($(this).empty());
                        // function to set someVar = div[index];
        }
    });
});

我不确定如何最好地完成此任务,所以如果有人有任何建议,我会很感激一些指导。

谢谢!

3 个答案:

答案 0 :(得分:2)

<div id="div0" class="draggableDiv">some cotent</div>
<div id="div1" class="draggableDiv">more content</div>
<div id="div2" class="draggableDiv">yet more content</div>

<div id='dropplace' class="droppableDiv">drop it here</div>

<script language='javascript'>

$(document).ready(function() {
    $('.draggableDiv').draggable({helper: 'clone'});
    $('.droppableDiv').droppable({
        accept: '.draggableDiv', //changed this, it was originally 'draggableRecipe'
        drop: function(ev, ui) { 

                //get the index of dropped draggable div
                var divIndex = $('div').index(ui.draggable)
                alert(divIndex) //alert the divIndex to see the result

                ui.draggable.clone().fadeOut("fast", 
                function() { 
                        $(this).fadeIn("fast") 
                }).appendTo($(this).empty());
        }
    });
});
</script>

测试过这个,它对我有用,希望对你也有用。祝你好运

答案 1 :(得分:0)

您应该能够使用

解析div的id
$.droppedItems = {};

var droppedId = $(this).attr('id').replace('droppable', '');
$.droppedItems[droppedId] = ui.draggable.attr('id').replace('div', '');

答案 2 :(得分:0)

drop: function(ev, ui) {行之后添加:

var droppedId = ui.draggable.attr("id");

之后droppedId将是您的div0div1div2之一 - 具体取决于丢弃的内容。