最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set multiple data on dataTransfer.setData - Stack Overflow

programmeradmin2浏览0评论

It's possible to set multiple using dataTransfer?

HTML

<tr class="notfirst"
    draggable="true"
    ondragstart="drag(event, '@Model.getFormat(item)', '@Model.getColor(item)')"
    ondragover="allowDrop(event)"
>

JS

function drag(ev, format, color) {
    ev.dataTransfer.setData("text", format);
    ev.dataTransfer.setData("text", color); 
}

I can correctly pass format and color to my JS function but I cant add both to dataTransfer because color replaces format. I tried also to pass an object but didn't work either.

It's possible to set multiple using dataTransfer?

HTML

<tr class="notfirst"
    draggable="true"
    ondragstart="drag(event, '@Model.getFormat(item)', '@Model.getColor(item)')"
    ondragover="allowDrop(event)"
>

JS

function drag(ev, format, color) {
    ev.dataTransfer.setData("text", format);
    ev.dataTransfer.setData("text", color); 
}

I can correctly pass format and color to my JS function but I cant add both to dataTransfer because color replaces format. I tried also to pass an object but didn't work either.

Share Improve this question edited Mar 14, 2019 at 16:35 vincrichaud 2,20820 silver badges35 bronze badges asked Mar 14, 2019 at 16:08 Daniel AlvesDaniel Alves 911 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

You may push your data to a JSON object, then convert this object to a string with JSON.stringify(). After that you will be able to pass the whole string to setData.

   let  obj = {prd_iId: 50 ,prd_sName: 'Ray Ban'};
   obj = {...obj, prd_sModel:'Aviator'};     
   e.dataTransfer.setData("text/plain", JSON.stringify(obj));

That will do what you want.

possible to set multiple using dataTransfer?

Yes.

If you don't want to serialize data you can simply set your data with different format arguments:

  ev.dataTransfer.setData('formatText', format);
  ev.dataTransfer.setData('colorText', color); 

get data like this

  const format = ev.dataTransfer.getData('formatText');
  const color  = ev.dataTransfer.getData('colorText'); 
发布评论

评论列表(0)

  1. 暂无评论