我正在尝试找出一种通过 javascript 的 event.dataTransfer 传递原生对象以进行拖放的方法.我正在编写 CMS 的前端编辑器部分,并希望用户能够拖放元素(许多不同类型的元素,从文件到图像到 HTML 片段到几乎任何东西).这就是为什么我想传递一个真实的对象,所以我可以将数据附加到它以指定为了知道如何呈现它而需要的东西.
I'm trying to figure out a way to pass a native object through javascript's event.dataTransfer for drag and drop. I'm writing the front end editor portion of a CMS, and want users to be able to drag and drop elements (of many different types, ranging from files to images to snippets of HTML to just about anything). That's why I want to pass a real object, so I can attach data to it to specify things that will be necessary in order to know how to render it.
一种解决方法是使用 jQuery 的 .data() 将对象附加到页面上的其他内容,然后简单地在 setData 中传递选择器字符串...但我并不特别喜欢这种 hack.
One workaround is to use jQuery's .data() to attach an object to something else on the page, and then simply pass the selector string in setData... but I don't particularly enjoy that hack.
这也可以通过 jQuery UI 的可拖放/可拖放来解决(我并不完全反对使用任何库),但由于 dropzone 位于 iframe 中,这实际上是最新 jQuery UI 中记录的错误(1.10.2).另外,如果可能的话,我强烈希望在本地进行.此应用中的库已经足够了.
This could also be solved with jQuery UI's draggable/droppable (and I'm not totally opposed to using any libraries), but since the dropzone is in an iframe, this is a actually a documented bug in the latest jQuery UI (1.10.2). Also, I would strongly prefer to do it natively if possible. There are already enough libraries in this app.
问题出在这里:http://jsfiddle.net/AHnh8/
var foo = {foo: "foo", bar: "bar"};
$dragme.on("dragstart", function(e) {
e.originalEvent.dataTransfer.setData("foo", foo);
});
$dropzone.on("dragenter", function(e) { e.preventDefault(); });
$dropzone.on("dragover", function(e) { e.preventDefault(); });
$dropzone.on("drop", function(e) {
console.log(e.originalEvent.dataTransfer.getData("foo")); // [Object object]
console.log(typeof e.originalEvent.dataTransfer.getData("foo")); // string
});
现在,在阅读了规范之后,我完全明白为什么会失败.我不明白的是,如何最终实现我想要的.
Now, after reading the specs, I totally understand why this fails. What I don't understand, is how to ultimately achieve what I want.
谢谢
你应该在使用 setData
之前将对象传递给 JSON.stringify
因为你只能存储字符串.
You should pass the object to JSON.stringify
before using setData
because you can only store strings.
var j = JSON.stringify(foo);
e.originalEvent.dataTransfer.setData("foo", j);
反之,你必须将字符串重新转换为对象:
And the other way round you have to reconvert the string to an object:
var obj = JSON.parse(e.originalEvent.dataTransfer.getData("foo"));
console.log("foo is:", obj);
查看 this 工作小提琴
这篇关于通过 dataTransfer 传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!