問題描述
我正在嘗試找出一種通過 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 傳遞對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!