从被拖动的元素中获取父数据元素 - 拖放功能

我正在尝试data-date在 JavaScript 中检索拖动对象的父数据属性。所以我想<td>从div“拖动我”的位置接收数据日期属性。


HTML 示例:


<td data-date="2/3/2020">

<div>drag me</div>

</td>


<td data-date="3/3/2020">

<-- DIV "Drag Me" will be dragged to this location --!>

</td>

我能够检索删除的数据日期属性,但无法弄清楚如何检索从数据日期属性中拖动的内容。


JS From 和 TO 当前代码


       dropped = ui.draggable,

       newDate = $(this).data('date'),

       console.log('Date From :' + dropped.data('date')); // needs to be found

       console.log('Date To:' + newDate); // Works correctly

javascript

拖放

元素

自定义数据属性


海绵宝宝撒
浏览 189回答 2
2回答

吃鸡游戏

我找到了一种解决方法,可以将信息从可拖动函数传递到可放置函数在下面的示例中,我首先从可拖动函数中的父元素获取数据日期值。检索到这些数据后,我们将值从可拖动的函数传递给可放置的函数。我们将变量命名为oldDate,以便我们可以通过调用“ui.draggable.data('oldDate')”在可放置函数中访问它。我会在下面为你们提供一个示例代码。可拖动功能:$(".drag").draggable({&nbsp; &nbsp; cursor: "crosshair",&nbsp; &nbsp; revert: "invalid",&nbsp; &nbsp; start: function(event, ui) {&nbsp; &nbsp; &nbsp; &nbsp; var oldDate = $(this).parent().data('date'); // get value from parent data-date attribute&nbsp; &nbsp; &nbsp; &nbsp; $(this).data('oldDate', oldDate); // pass variable to droppable function&nbsp; &nbsp; }});可丢弃功能:&nbsp;$("td[data-date]").droppable({&nbsp; &nbsp; accept: ".drag",&nbsp;&nbsp; &nbsp; activeClass: "over",&nbsp; &nbsp; drop: function(event, ui) {&nbsp; &nbsp; &nbsp; &nbsp; var displayOldDate = ui.draggable.data('oldDate'); // access the variable saved in draggable function&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; console.log('Dragged from: ' + displayOldDate);&nbsp; &nbsp; }&nbsp;});

HUWWW

管理它的方法很少我最好在开始拖动时将初始父元素保存到某个变量中。另一种选择可能是在拖动元素本身上拥有所有需要的数据
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript