假设我的左侧有一些可放置的div,名为1 - 4区。
<div id="zone1"></div>
<div id="zone2"></div>
<div id="zone3"></div>
<div id="zone4"></div>
我右手边的一些可拖动物品
<div id="drag1">Apple</div>
<div id="drag2">Banana</div>
<div id="drag3">Kiwi</div>
<div id="drag4">Orange</div>
我知道我可以将它们设置为可拖动和可放置,如下所示:
for (var i=1;i<=4;i++)
{
var x = "zone" + i;
$(x).droppable();
}
for (var i=1;i<=4;i++)
{
var x = "drag" + i;
$(x).draggable();
}
现在,当一个水果落入一个区域时,我将如何触发一个函数启动,该区域将给我放下掉落的区域(zone1,zone2等)以及掉落在那里的水果。理想情况下,我不想要水果名称,我想要一个与水果相关联的id可能隐藏在一个隐藏的输入标签或什么东西?
答案 0 :(得分:1)
我建议你这样做,而不是你拥有的。
<div id="zone1" class="droppable"></div>
<div id="zone2" class="droppable"></div>
<div id="zone3" class="droppable"></div>
<div id="zone4" class="droppable"></div>
<div id="drag1" class="draggable">Apple</div>
<div id="drag2" class="draggable">Banana</div>
<div id="drag3" class="draggable">Kiwi</div>
<div id="drag4" class="draggable">Orange</div>
然后为你的剧本:
var fruit_id = '';
var dropbox_id = '';
$( '.draggable' ).draggable();
$( '.droppable' ).droppable({
drop: function( event, ui ) {
fruit_id = $(ui.draggable).attr('id');
dropbox_id = $( this ).attr('id');
/* DO SOMETHING HERE */
}
});
/* Or do something here! */
希望有所帮助!
答案 1 :(得分:0)
$(init)
function init() {
$('#makeMeDraggable').draggable();
$('#makeMeDroppable').droppable( {
drop: handleDropEvent
} );
}
function handleDropEvent( event, ui ) {
var draggable = ui.draggable;
alert( 'The square with ID "' + draggable.attr('id') + '" was dropped onto me!' );
}
答案 2 :(得分:0)
您可以使用drop
互动的droppable
事件。在此事件中,处理程序$(this)
指向droppable元素,其中ui.draggable指向可拖动元素。
for (var i=1;i<=4;i++)
{
var x = "zone" + i;
$(x).droppable({
drop: function(){
//This will alert the id of container in which fruit is dropped
alert($(this).attr('id'));
//This will alert the id of fruit container which is dragged
alert($(ui.draggable).attr('id'));
}
});
}
for (var i=1;i<=4;i++)
{
var x = "drag" + i;
$(x).draggable();
}
答案 3 :(得分:-1)
<style>
.zones>div{ border:solid 1px gray; background-color:yellow; padding:20px;margin:5px;}
</style>
<div class="zones">
<div id="zone1"></div>
<div id="zone2"></div>
<div id="zone3"></div>
<div id="zone4"></div>
</div>
<div id="drag1" fruitid="1">Apple</div>
<div id="drag2" fruitid="2">Banana</div>
<div id="drag3" fruitid="3">Kiwi</div>
<div id="drag4" fruitid="4">Orange</div>
<script>
$("div[id*='zone']").droppable({
accept: "div[id*='drag']",
drop: function( event, ui ) {
alert( ui.draggable.text() + " with fruitid = "+ ui.draggable.attr("fruitid")+" added to " + $(this).attr("id"));
$( "<div/>" ).text( ui.draggable.text()).appendTo( this );
}
})
$('div[id*="drag"]').draggable({helper: "clone"});
</script>