Получение атрибута данных отброшенного объекта в сортируемый div

У меня есть список предметов:

<div class='item' data-itemtype="title">Title</div>

Что я хочу попасть в сортируемый div.

<div class="content"></div>

Я использую этот код:

$( document ).ready( function () {
    $( '.item' ).draggable( {
        helper: function ( e ) {
            return $( '<div>' ).addClass( 'block' ).text( $( e.target ).text() );
        },
        connectToSortable: ".content",
        opacity: .8,
    } );
    ///     
    $( '.content' ).sortable( {
        placeholder: 'block-placeholder',
        update: function ( event, ui ) {
            // turn the dragged item into a "block"
            ui.item.addClass( 'block' );
            var itemtype = ui.item.data('itemtype');
            alert( 'this: '+itemtype );
        }
    } );        
    //      
} );

Все работает нормально, но мне нужно получить атрибут данных из элемента, чтобы я мог передать его другому сценарию. Но результат атрибута данных продолжает отображаться как "неопределенный". Я не могу понять, что я делаю не так. Спасибо за любую помощь.

2 ответа

Проблема в том, что при перетаскивании .item в .content, новый элемент внутри .content не содержит data-itemtype приписывать. Чтобы нацелиться на этот атрибут, вы захотите обратиться к элементу напрямую var itemtype = $('.item').data('itemtype'),

Это можно увидеть в следующем:

$(document).ready(function() {
  $('.item').draggable({
    helper: function(e) {
      return $('<div>').addClass('block').text($(e.target).text());
    },
    connectToSortable: ".content",
    opacity: .8,
  });
  ///     
  $('.content').sortable({
    placeholder: 'block-placeholder',
    update: function(event, ui) {
      // turn the dragged item into a "block"
      ui.item.addClass('block');
      var itemtype = $('.item').data('itemtype');
      alert('this: ' + itemtype);
    }
  });
  //      
});
.item, .content {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>

<div class='item' data-itemtype="title">Title</div>
<div class="content"></div>

Кроме того, вам нужно добавить атрибут к элементу, когда он копируется, с чем-то вроде $(ui.item).attr('data-itemtype', $('.item').data('itemtype')):

$(document).ready(function() {
  $('.item').draggable({
    helper: function(e) {
      return $('<div>').addClass('block').text($(e.target).text());
    },
    connectToSortable: ".content",
    opacity: .8,
  });
  ///     
  $('.content').sortable({
    placeholder: 'block-placeholder',
    update: function(event, ui) {
      // turn the dragged item into a "block"
      ui.item.addClass('block');
      $(ui.item).attr('data-itemtype', $('.item').data('itemtype'));
      var itemtype = ui.item.data('itemtype');
      alert('this: ' + itemtype);
    }
  });
  //      
});
.item, .content {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>

<div class='item' data-itemtype="title">Title</div>
<div class="content"></div>

Вот как я смог решить эту проблему

HTML

@foreach($categories as $data)
  <tr class="sortme">
     <td> {{ $data->category_name }} </td>
     <td> {!! \Str::limit($data->category_description, 50, ' ...')  !!} </td>
     <td> {{ count( $data->products ) }} Product/s</td>
     <td>
       <a class="btn btn-info btn-xs" href="{{ route('category.edit', $data->id) }}"> View/Edit </a>
     </td>
  </tr>
@endforeach

jQueryUI

$( "tbody" ).sortable({
    items : '.sortme',
    start   : function(event, ui) {
        $(this).attr('data-currentindex', ui.item.index());
    },
    update : function (event, ui) {
        var current_position    = $(this).attr('data-currentindex'),
            category_to_move    = ui.item[0].dataset.category_id,
            desired_position    = ui.item.index();

        console.log( ui.item[0].dataset.category_id );

        $.ajax({
          // my ajax stuff
        })
    }
});

В основном я просматривал ui.item

Надеюсь, это поможет кому-то в будущем.

Спасибо Obsidian - ты поставил меня на правильный путь. Понял, что мне пришлось повторно добавить атрибут данных во время перетаскивания, а затем я мог получить доступ к данным, когда они были отброшены.

Мое решение:

$( document ).ready( function () {
    $( '.item' ).draggable( {
        helper: function ( e ) {    
            var itemvar = $(this).data('itemtype');
            return $('<div data-itemtype="'+itemvar+'">').addClass('block').text($(e.target).text());
        },
        connectToSortable: ".content",
        opacity: .8,
    } );
    ///     
    $( '.content' ).sortable( {
        placeholder: 'block-placeholder',
        update: function ( event, ui ) {
            // turn the dragged item into a "block"
            ui.item.addClass( 'block' );
            $(ui.item).attr('data-itemtype', $(this).data('itemtype'));
            var itemtype = ui.item.data('itemtype');
            alert('this: ' + itemtype);
        }
    } );        
    //      
} ); 

Спасибо всем за помощь!!

Другие вопросы по тегам