如何使用html5 event.dataTransfer传输整个元素?

Tha*_*ung 5 html javascript jquery drag-and-drop

我想记住或获取当前拖动元素的数据。这就是我所做的:

$('.source_element').on('dragstart', function(e){
   e.originalEvent.dataTransfer.setData("source", this); 
});

$('.destination').on('drop', function(e){
   var source = e.originalEvent.dataTransfer.getData('source');
   console.log(source);
   console.log(source.className);
   console.log($(source));
   $(this).html($(source).html());

   e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)

第一个 console.log 显示[object HTMLDivElement]为字符串,而不是对象,第二个undefined、第三个抛出错误。

所以我怀疑dataTransfer.setData只接受字符串形式的数据,不允许对象。如果是这样的话,你如何解决这个问题,我如何在不知道其具体ID的情况下记住哪个元素被拖动?

Mus*_*usa 4

只需使用一些字符串来唯一标识元素,例如为每个元素提供一个 id 或数据属性

$('.source_element').on('dragstart', function(e){
   var id = 'drag-'+(new Date()).getTime();
   this.id = id;
   //$(this).attr('data-drag', id);
   e.originalEvent.dataTransfer.setData("source", id); 
});

$('.destination').on('drop', function(e){
   var source = e.originalEvent.dataTransfer.getData('source');
   console.log(source);
   console.log($('#'+source));
   $(this).html($('#'+source).html());
   //console.log($('[data-id="'+source+'"]'));
   //$(this).html($('[data-id="'+source+'"]').html());

   e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)