search

Home  >  Q&A  >  body text

Why dataTransfer.clearData doesn't work?

 function dropStart(e){
     e.dataTransfer.setData("Text",e.target.id);
     //e.dataTransfer.clearData();在这里调用clearData(),drop函数里的getData才会返回空值。
     }
 function drop(e){
     var id=e.dataTransfer.getData("Text");
     e.dataTransfer.clearData();
     console.log(e.dataTransfer.getData("Text"));//还可以获得id
     }

After calling e.dataTransfer.clearData() in the drop function, executing getData("Text") will also return the value in setData(), so how to use clearData(), or should it be executed in the drop function Will the data saved by dataTransfer.setData() be automatically deleted after completion?

習慣沉默習慣沉默2794 days ago721

reply all(2)I'll reply

  • 滿天的星座

    滿天的星座2017-05-18 10:58:51

    There is no problem with my output. DataTransfer.clearData() can only be used in the dragstart event.

    
    <p id="source" draggable="true">测试数据</p>
    
    var draggable = document.getElementById('source');
    
    draggable.addEventListener('dragstart', drop);
    function drop (e) {  
      e.dataTransfer.setData("Text",e.target.id);
      // 输出id:source
      alert('id:' + e.dataTransfer.getData("Text"));
      e.dataTransfer.clearData();
      // 输出id:
      alert('id:' + e.dataTransfer.getData("Text"));
    }

    reply
    0
  • 阿神

    阿神2017-05-18 10:58:51

    clearData() can only be used in the dragStart function. Calling clearData() in the drop function is useless and unnecessary, because the data saved by setData() is created when the drag starts, and it is not used when the drag is dropped. That is, when dragging ends, the data saved by setData() will be destroyed.

    reply
    0
  • Cancelreply