Javascript jQuery:拖放:找到目标的 id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3943868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:46:43  来源:igfitidea点击:

jQuery : drag and drop : find the id of the target

javascriptjquery

提问by Thomas John

I am developing a drag and drop app. I have a DIV that is draggable along the document and there are some other divs in the document, I can drag one div to other divs, but how can I find the id of the div to which I dropped the dragging DIV,

我正在开发一个拖放应用程序。我有一个可沿文档拖动的 DIV,文档中还有一些其他 div,我可以将一个 div 拖到其他 div,但是如何找到我将拖动的 DIV 拖放到的 div 的 id,

I just want to know the id of the target DIV after placing another DIV over it.

在将另一个 DIV 放在目标 DIV 上之后,我只想知道它的 id。

Thanks

谢谢

回答by Mottie

You should be able to get the ID of the target from this.idfrom inside the event functions (demo)

您应该能够this.id从事件函数内部获取目标的 ID (演示

$(".droppable").droppable({
    drop: function(event, ui) {
        $(this).addClass("ui-state-highlight").find("p").html("Dropped in " + this.id);
    },
    over: function(event, ui) {
        $('.display').html( this.id );
    }
});

Updated demoto make it clear that this.idworks in any of the events.

更新了演示以明确说明this.id适用于任何事件。

回答by phorgan1

If you use event delegation, though, thiswill be some parent of the target div. In this case you could use:

但是,如果您使用事件委托,将是目标 div 的某个父级。在这种情况下,您可以使用:

var handleDrop=function(e)
{
    var target=e.target || e.srcElement;
    var id=target.id;
    // do something with it
}

回答by ashes999

You can use an event handler; it gives you both the one dragged and the one dropped on.

您可以使用事件处理程序;它给你一个拖拽和一个放下。

function handleDropEvent(event, ui) {
  alert('Dropped ' + ui.draggable.attr('id') + ' onto ' + event.target.id);
}

$('#someContainer').droppable({
  drop: handleDropEvent
})