jQuery Drag And Drop Using Live Events

2019-01-03 02:15发布

I have an application with a long list that changes frequently, and I need the items of that list to be draggable.

I've been using the jQuery UI draggable plugin, but it is slow to add to 400+ list items, and has to be re-added every time new list items are added.

Does anyone know of a plugin similar to the jQuery UI draggable plugin that uses jQuery 1.3's .live() events? This would solve both problems.

10条回答
Emotional °昔
2楼-- · 2019-01-03 02:55

You could make wrapper function like this:

function liveDraggable(selector, options){
  jQuery(selector).live("mouseover",function(){
    if (!jQuery(this).data("init")) {
      jQuery(this).data("init", true);
      jQuery(this).draggable(options);
    }
  });
}

(I use prototype with jQuery - that's why i placed jQuery() instead of $())

And now instead of $(selector).draggable({opts}) use liveDraggable(selector, {opts})

查看更多
不美不萌又怎样
3楼-- · 2019-01-03 02:59

This is a sample of code that perfectly worked for me

$('.gadgets-column').live('mouseover',function(){
    $(this).draggable();
});
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-03 03:01

An updated version that does not use live as it is deprecated:

function liveDraggable(selector, options) {
    $(document).on('mouseover', selector, function () {
        if (!$(this).data("init")) {
            $(this).data("init", true);
            $(this).draggable(options);
        }
    });
}
查看更多
The star\"
5楼-- · 2019-01-03 03:02

Combining the best answers from @john and @jasimmk:

Using .live:

$('li:not(.ui-draggable)').live('mouseover',function(){
    $(this).draggable(); // Only called once per li
});

.live is deprecated though, better to use .on:

$('ul').on('mouseover', 'li:not(.ui-draggable)', function(){
    $(this).draggable();  // Only called once per li
});

As @john explained, .ui-draggable is automatically added to draggable methods, so by excluding that class with the selector, you ensure that draggable() will only be called once on each element. And using .on will reduce the scope of the selector, improving performance.

查看更多
男人必须洒脱
6楼-- · 2019-01-03 03:07
$("html divs to drag").appendTo("#layoutDiv").draggable(options);

JSFiddle

查看更多
【Aperson】
7楼-- · 2019-01-03 03:09

An old question. But threedubmedia has drag and drop plugin with live (as of v 1.7 known as simply "on") support. http://threedubmedia.com/code/event/drop Haven't used it to much so I can't account for it performance, etc. but looks reasonable.

查看更多
登录 后发表回答