gpt4 book ai didi

javascript - 如何使用 html5 event.dataTransfer 传输整个元素?

转载 作者:可可西里 更新时间:2023-11-01 12:50:13 27 4
gpt4 key购买 nike

我想记住或获取当前拖动元素的数据。这就是我所做的:

$('.source_element').on('dragstart', function(e){
e.originalEvent.dataTransfer.setData("source", this);
});

$('.destination').on('drop', function(e){
var source = e.originalEvent.dataTransfer.getData('source');
console.log(source);
console.log(source.className);
console.log($(source));
$(this).html($(source).html());

e.preventDefault();
});

第一个 console.log 将 [object HTMLDivElement] 显示为字符串,而不是对象,第二个 undefined,第三个抛出错误。

所以我怀疑 dataTransfer.setData 只接受数据作为字符串,不允许对象。如果是这样,你如何解决这个问题,我如何在不知道其具体 ID 的情况下记住正在拖动的是哪个元素?

最佳答案

只需使用一些字符串来唯一标识元素,例如为每个元素指定一个 id 或数据属性

$('.source_element').on('dragstart', function(e){
var id = 'drag-'+(new Date()).getTime();
this.id = id;
//$(this).attr('data-drag', id);
e.originalEvent.dataTransfer.setData("source", id);
});

$('.destination').on('drop', function(e){
var source = e.originalEvent.dataTransfer.getData('source');
console.log(source);
console.log($('#'+source));
$(this).html($('#'+source).html());
//console.log($('[data-id="'+source+'"]'));
//$(this).html($('[data-id="'+source+'"]').html());

e.preventDefault();
});

关于javascript - 如何使用 html5 event.dataTransfer 传输整个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17012375/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com