jQuery UI Draggable/Sortable - Get reference to new item

前端 未结 3 2042
半阙折子戏
半阙折子戏 2020-12-14 19:31

I am using the jQuery UI Draggable/Sortable demo (http://jqueryui.com/demos/draggable/#sortable) for the basis of my project. I need to get a reference to the

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 20:11

    In the demo you reference, there's actually a bug; after you drag an item down it inserts a cloned li with an id which is a duplicate of its brother's into the DOM, so beware (a bug was filed about this but there's no activity around it).

    I did a few things to achieve this:

    1. To get around the limitation of the demo that I described above, instead apply a class to the draggable items that will be linked to the sortable:

      • Drag me down
    2. Make items with that class draggable, instead of selecting an element by id:

       $(".new-item").draggable({
           connectToSortable: "#sortable",
           helper: "clone",
           revert: "invalid"
       });
      
    3. Tap into the stop event of the sortable, and perform some simple logic about the item that was dropped, leveraging the fact that an item with the class new-item could only have been dropped (and isn't simply an existing item in the sortable):

      $("#sortable").sortable({
          revert: true,
          stop: function(event, ui) {
              if (ui.item.hasClass("new-item")) {
                  // This is a new item
                  ui.item.removeClass("new-item");
                  ui.item.html("HI");
              }
          }
      });
      

    Note that you could use the data-* attribute instead of adding a helper class.

    Here's a working example: http://jsfiddle.net/andrewwhitaker/twFCu/

    Hope that helps.

提交回复
热议问题