jQuery UI Drop/Drag data из sql нельзя перетаскивать/отбрасывать

Я играю с jQuery UI Drop/Drap, используя предоставленный пример Photo Manager с сайта jqueryui.com. Чего я пытаюсь добиться, так это использовать его как менеджер фотографий, но с данными, автоматически сгенерированными из базы данных sql. Мне удалось заполнить перетаскиваемый <div> данными из базы данных, а изображения можно перетаскивать в отбрасываемый <div>, как в примере, и поэтому я сохраняю эти данные обратно в базу данных (другую таблицу), поэтому в следующий раз, когда пользователи перезарегистрируются или обновите страницу, они смогут увидеть изображения, которые были удалены в выпадающем <div>, пока все хорошо. Проблема в том, что данные, сгенерированные для перетаскиваемого <div>, нельзя перетаскивать, только изображения, которые были удалены из перетаскиваемого <div> без обновления страницы, можно перетаскивать и возвращать обратно в перетаскиваемый <div>.

код пользовательского интерфейса jquery

$(function() {

      var $available_for_share = $( "#available-for-share" ),
      $currently_sharing = $( "#currently-sharing" );

      // let the available_for_share items be draggable
      $( "li", $available_for_share ).draggable({
            cancel: "a.ui-icon", // clicking an icon wont initiate dragging
            revert: "invalid", // when not dropped, the item will revert back to its initial position
            containment: $( "#sharing" ).length ? "#sharing" : "document", // stick to demo-frame if present
            helper: "clone",
            cursor: "move"
      });

      // let the available_for_share be droppable as well, accepting items from the currently-sharing
      $available_for_share.droppable({
            accept: "#currently-sharing  li",
            activeClass: "custom-state-active",
            drop: function( event, ui ) {
                  currently_sharing( ui.draggable );
            }
      });

      // let the currently-sharing be droppable, accepting the available_for_share items
      $currently_sharing.droppable({
            accept: "#available-for-share > li",
            activeClass: "ui-state-highlight",
            drop: function( event, ui ) {
                  available_for_share( ui.draggable );
            }
      });


      function available_for_share( $item ) {
            var arr = {};
            arr['list_id'] = list_id();
            arr['share_with'] = $item.attr('id');
            $.post('<?= site_url() ?>/lists/js_share_with', arr,function(str){
                  str = $.parseJSON(str);
                  if(str['status'] == 0){
                        info_bar(str['status'],str['msg']);
                  } else {
                        info_bar(str['status'],str['msg']);
                        $item.fadeOut(function() {
                              var $list = $( "ul", $currently_sharing ).length ?
                                    $( "ul", $currently_sharing ) :
                                    $( "<ul class='available-for-share ui-helper-reset'/>" ).appendTo( $currently_sharing );
                              $item.find( "a.ui-icon-trash" ).remove();
                              $item.appendTo( $list ).fadeIn();
                        });
                  }
            })

      }


      function currently_sharing( $item ) {
            var arr = {};
            arr['list_id'] = list_id();
            arr['stop_sharing'] = $item.attr('id');
            $.post('<?= site_url() ?>/lists/js_stop_sharing', arr,function(str){
                  str = $.parseJSON(str);
                  if(str['status'] == 0){
                        info_bar(str['status'],str['msg']);
                  } else {
                        $item.fadeOut(function() {
                              $item
                              .appendTo( $available_for_share )
                              .fadeIn();
                        });
                        info_bar(str['status'],str['msg']);
                  }                                    
            })
      }

HTML

<div id="sharing" class="col3 center">

<h2>Share this list</h2>
<span style="font-size:0.8em;">Drag and drop at the bottom box the images you want to share.</span>
<br />
<? if (is_array($available)) : ?>
      <div class="ui-widget ui-helper-clearfix">
            <hr>
            <span style="font-size:0.8em;">available for sharing</span><br />
            <ul id="available-for-share" class="available-for-share ui-helper-reset ui-helper-clearfix  ui-state-default">&nbsp;
                  <? foreach ($available as $k) : ?>
                        <li id="<?= $k['imageID'] ?>" class="ui-widget-content ui-corner-tr">
                              <img src="http://somedomain/images/<?= $k['imageID'] ?>_64.jpg" alt="<?= $k['imageName'] ?>" width="52" height="52" />
                        </li>

                  <? endforeach ?>
            </ul>
            <span style="font-size:0.8em;">shared with</span><br />
            <div id="currently-sharing" class="ui-widget-content ui-state-default ui-droppable">
                  <? if (is_array($currently_sharing_with)) : ?>
                        <ul class="available-for-share ui-helper-reset">
                        <? foreach ($currently_sharing_with as $k) : ?>
                              <li id="<?= $k['imageID'] ?>" class="ui-widget-content ui-corner-tr ui-draggable" style="display: list-item;">
                                    <img src="http://somedomain/images/<?= $k['imageID'] ?>_64.jpg" alt="<?= $k['imageName'] ?>" width="52" height="52" />
                              </li>
                        <? endforeach ?>
                        </ul>
                  <? endif ?>
            </div>

      </div>

<? else : ?>
      <p>No images</p>
<? endif ?>

</div>

Код jquery находится внутри <script> и запускается сразу после извлечения данных из базы данных.


person afarazit    schedule 23.09.2011    source источник


Ответы (2)


Нашел решение, мне тоже пришлось сделать $currently_sharing перетаскиваемым, его можно было только сбрасывать.

  // let the $currently_sharing items be draggable
  $( "li", $currently_sharing ).draggable({
        cancel: "a.ui-icon", // clicking an icon won't initiate dragging
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: $( "#sharing" ).length ? "#sharing" : "document", // stick to demo-frame if present
        helper: "clone",
        cursor: "move"
  });
person afarazit    schedule 23.09.2011

Попробуйте использовать подключаемый модуль livequery, http://docs.jquery.com/Plugins/livequery . Возможно, вам нужно использовать функцию live для вновь добавленных элементов.

$( "li", $available_for_share ).livequery(function(){
         $(this).draggable({
            cancel: "a.ui-icon", 
            revert: "invalid", 
            containment: $( "#sharing" ).length ? "#sharing" : "document", 
            helper: "clone",
            cursor: "move"
          });
});

сделать то же самое и для других функций

person Jayantha Lal Sirisena    schedule 23.09.2011
comment
проблема заключается не в перетаскивании сгенерированных данных из $available_for_share, а из $currently_sharing. Сгенерированные данные в этом <div> нельзя перетаскивать/удалять. Я все равно пробовал .livequery()и .live(), и это не сработало. - person afarazit; 23.09.2011