简体   繁体   English

是否可以在动态创建的元素中使用HTML5拖放?

[英]Is it possible to use the HTML5 drag-and-drop in dynamically created elements?

Edit: I know this looks like a duplicate question, but it's very specific to the HTML5 drag events. 编辑:我知道这看起来像一个重复的问题,但它非常特定于HTML5拖动事件。 I'm not having a problem adding in jQuery events, just the HTML5 drag and drop functionality. 我在添加jQuery事件时没有问题,只是HTML5拖放功能。

I've used basic jQuery several times to add drag-and-drop functionality to a page, but I'd like to use the new HTML5 drag-and-drop feature for my current project. 我已经多次使用基本的jQuery来为页面添加拖放功能,但我想为我当前的项目使用新的HTML5拖放功能。 Drag works great for any element I include in the HTML, but I don't seem to be able to add elements dynamically and have them be draggable. 拖动适用于我在HTML中包含的任何元素,但我似乎无法动态添加元素并使它们可拖动。 I suspect this is because all the draggable event listeners are bound when the page is loaded, before my new elements are created. 我怀疑这是因为在创建新元素之前,在加载页面时绑定了所有可拖动的事件侦听器。 Has anyone had any luck using HTML5 to make dynamically added elements draggable? 有没有人有运气使用HTML5来动态添加元素可拖动? Or is there a way to re-bind event listeners without reloading the page? 或者有没有办法重新绑定事件侦听器而无需重新加载页面?

Using .bind() with any of the HTML5 drag events doesn't seem to work. .bind()与任何HTML5拖动事件一起使用似乎不起作用。 ie,

$(newElement).bind('drag', function(e){
  console.log('do you even drag, bro?');
});

won't ever fire, though .bind() with a click event works fine. 虽然.bind()与点击事件工作正常,但不会激发。 I'm guessing this is because "drag" means nothing to jQuery. 我猜这是因为“拖”对jQuery没什么意义。 I am including the draggable="true" HTML tag in the new element, by the way. 顺便说一句,我在新元素中包含了draggable="true" HTML标记。

So, anyone have success stories for binding the HTML5 drag events to dynamically created elements, or is it not possible? 那么,任何人都有将HTML5拖动事件绑定到动态创建元素的成功案例,或者这是不可能的? Thanks! 谢谢!

There are two ways to accomplish this. 有两种方法可以实现这一目标。 The first is to use some kind of ancestor element that will exist at the time your bind() is called: 第一种是使用在调用bind()时存在的某种祖先元素:

$('.someParent').on('drag', '.newElement', function(){
    console.log('do you even drag, bro?');
});

The second is to structure your code such that your bind function gets called after your newElement gets created: 第二个是构造代码,以便在创建newElement之后调用bind函数:

var $newElement = $('<div class="newElement"></div>');

$newElement.on('drag', function(e){
    console.log('do you even drag, bro?');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM