使用 Jquery 将信息附加到“数据传输”

Attach informations to `dataTransfer` with Jquery

在 dragstart 上,我正在尝试将文本附加到拖动的图像上。以便我稍后在 drop 方法中识别它:

 var drag = function(event){
    event.originalEvent.dataTransfer.setData('text', 'ww');

但不知何故,即使直接在附加文本后,我也无法再访问它:它是 undefinded

 event.originalEvent.dataTransfer.getData('text')

如何将信息附加到 dataTransfer-对象并稍后在 drop-事件中访问它们? 谢谢

您可以尝试使用此代码:

var allowDrop = function(ev) {
  ev.preventDefault();
};

var drop = function(ev) {
  var attached_text = ev.originalEvent.dataTransfer.getData("text"); 
  
  //HERE I TRY TO GET THE ATTACHED TEXT
  //ITS EMPTY
  $('#attach_1').text(attached_text);
};
  

var drag = function(event){
  event.originalEvent.dataTransfer.setData('text', 'ww');
  
  var attached_text  = (event.originalEvent.dataTransfer.getData('text'));
  
  //RIGHT AFTER I ATTACHED THE TEXT ITS NOT ACCESIBLE
  $('#attach_2').text(attached_text);
}


$('*[data-dragname="tree_icon_drag"]').on('drag', drag);

$('#drop').on('drop',  drop);
$('#drop').on('dragover', allowDrop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="attach_1"></p>
<p id="attach_2"></p>
         
           
           <img src="http://agarwal.seas.upenn.edu/wp-content/uploads/2011/01/person_default_208x208-1.png" data-dragname="tree_icon_drag"/>
         

<div id="drop" style="background-color:red; width:300px; height:300px">
  
</div>

您在 dragstart 事件中设置数据而不是 drag 事件

var dragstart = function(event){
  event.originalEvent.dataTransfer.setData('text', 'ww');
  var attached_text  = (event.originalEvent.dataTransfer.getData('text'));
  $('#attach_2').text(attached_text);  
};
$('*[data-dragname="tree_icon_drag"]').on('dragstart', dragstart);

演示

var allowDrop = function(ev) {
  ev.preventDefault();
};

var drop = function(ev) {
  var attached_text = ev.originalEvent.dataTransfer.getData("text"); 
  $('#attach_1').text(attached_text);
};

var drag = function(event){};
var dragstart = function(event){
  event.originalEvent.dataTransfer.setData('text', 'ww');
  var attached_text  = (event.originalEvent.dataTransfer.getData('text'));
  $('#attach_2').text(attached_text);  
};
$('*[data-dragname="tree_icon_drag"]')
    .on('drag', drag)
    .on('dragstart', dragstart);

$('#drop').on('drop',  drop)
          .on('dragover', allowDrop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="attach_1"></p>
<p id="attach_2"></p>
<img src="http://agarwal.seas.upenn.edu/wp-content/uploads/2011/01/person_default_208x208-1.png" data-dragname="tree_icon_drag"/>
<div id="drop" style="background-color:red; width:300px; height:300px"></div>