开发者

jquery UI draggable with live

this is a draggable sortable example on the jqueryui website, i need to use live() with this (I think) because the elements are created through ajax, does anybody know how to apply the live event to the following?

<script>开发者_JS百科
    $(function() {
        $( "#sortable" ).sortable({
            revert: true
        });
        $( "#draggable" ).draggable({
            connectToSortable: "#sortable",
            helper: "clone",
            revert: "invalid"
        });
        $( "ul, li" ).disableSelection();
    });
    </script>


I don't think it is possible to do the live event as you want it. The best option you have is to use a callback function when you add a new element to the list and reenable the new object to be draggable each time there is a new element.

Something like this:

// Call to add a new element
$.ajax({
  url: 'addElem',
  success: function(data) {
    $( "#newDraggableObject" ).draggable({
        connectToSortable: "#sortable",
        helper: "clone",
        revert: "invalid"
    });
  }
});


You don't have to use live with this (and I don't think you can), just hook them up once you've added them, in the success handler. For instance, if using load:

$("#target").load("your url", function() {
  // Replace the selectors below to match what you load
  $( "#target *[data-name=sortable]" ).sortable({
      revert: true
  });
  $( "#target *[data-name=draggable]" ).draggable({
      connectToSortable: "#target *[data-name=sortable]",
      helper: "clone",
      revert: "invalid"
  });
  $(this).find( "ul, li" ).disableSelection();
});

Live Example

That uses this modified HTML from the jQuery UI demo page (just replaced id values with data-name instead, so they don't have to be unique):

<ul>
  <li data-name='draggable' class="ui-state-highlight">Drag me down</li>
</ul>

<ul data-name="sortable">
  <li class="ui-state-default">Item 1</li>
  <li class="ui-state-default">Item 2</li>
  <li class="ui-state-default">Item 3</li>
  <li class="ui-state-default">Item 4</li>
  <li class="ui-state-default">Item 5</li>
</ul>


I had the exact same problem and I think that it is a much better idea to solve this problem using a JQuery addin method:

//Add draggable feature:
//Define a setup method for the draggable config so we can reuse it for dynamic elements
$(function() {
    jQuery.fn.draggableSetup = function draggableSetup() {
        this.draggable(
        {
            // enter your custom draggable code here...
        });
        return this;
    }
});

//Apply the draggable config your dynamic elements after adding them
$("#dynamic_element_id").draggableSetup();

Thanks to this post for the answer.

This gives you a reusable solution and you don't have to repeat your implementation for each ajax method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜