【问题标题】:Drag & Drop HTML 5 jQuery: e.dataTransfer.setData() with JSON拖放 HTML 5 jQuery:带有 JSON 的 e.dataTransfer.setData()
【发布时间】:2012-03-02 12:49:33
【问题描述】:

这是我的拖动开始:

dragstart: function(e) {
    $(this).css('opacity', '0.5');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('application/json', {
        id: $(this).attr('id'),
        header: $('header', this).text()
    });
},

我想传递一些信息,例如 id 和 text。我的下降是:

drop: function(e) {
    var data = e.dataTransfer.getData('application/json');
    alert(data);
    $(this).attr('id', data.id);
    $('header', this).text(data.header);
},

但数据未定义,我无法访问我的数据。方法对吗?

谢谢!

【问题讨论】:

标签: html drag-and-drop


【解决方案1】:

在拖动开始

var testjson = {name:"asd",tall:123};
e.dataTransfer.setData("text/plain",JSON.stringify(testjson));
e.dataTransfer.effectAllowed = "copy";

下拉

var data = e.dataTransfer.getData("text/plain");
console.log(JSON.parse(data));

你会得到

Object {name: "asd", tall: 123} 

在控制台日志中

【讨论】:

  • 然而,默认情况下,这允许用户将 json 字符串放在任何 元素上,这可能不是有意的。
  • 如果有办法传递实际的json对象会更方便。很遗憾你必须把它串起来。
【解决方案2】:

如果你在你的 dragstart 函数中包含一个 effectAllowed,比如:

e.dataTransfer.effectAllowed = 'move';

那么我的理解是你需要在drop函数中定义一个等价的dropEffect:

e.dataTransfer.dropEffect = 'move';

【讨论】:

    猜你喜欢
    • 2012-12-06
    • 2012-03-20
    • 2011-09-02
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2013-01-11
    相关资源
    最近更新 更多