2016-03-24 54 views
1

這可能是一個簡單的問題,但我怎樣才能替換我從ajax調用的HTML拖動的東西?所以,如果可拖動的項目只是'文本'項目(如下面的HTML片段),當我拖動的東西,我通過幫助器方法使用'圖像',我怎麼可以'放'不是使用它們中的任何一個,但插入從ajax調用返回的html。JQuery的可排序和可拖動 - 用Ajax結果替換拖動的內容

我在哪裏進行調用(順便說一下,使用'輸入類型'值的Ajax調用來獲取正確的HTML)?

如何防止默認的「拖動項目」被插入?即我不希望div放入或輔助方法圖像....

我需要添加像droppable還是我在sortable上做這個事情就像received事件(類型的作品,可以' t刪除圖像,但從幫助方法)??? (我一直在嘗試這兩個,而ajax調用工作,我得到的數據等,因爲我不知道如何防止默認的東西被丟棄我不知道'我'取代'什麼'結果'從呼叫...)

$("#desktoplayout").sortable({ 
    receive: function (event, ui) { 
     $(this).append('<div>html from ajax call</div>'); // kind of works... but the image from the 'helper method' on the 'draggable' is still there. 
    } 
}); // A sortable list of stuff into which things are dragged. 

var input-type; 

$("#draggableItems .item").draggable({ 
    connectToSortable: "#desktoplayout", 
    helper: function (event) { 
     return "<div class='item'><img src='/Images/Header.png' /></div>"; 
    }, 
    start: function (event, ui) { 
     input-type = $(this).find('.preview').data("input-type"); 
    }, 
    drag: function(e, t) { 
    }, 
    stop: function(e, t) { 
    } 
}); 

<div id="draggableItems"> 
    <div class="item"> 
     <div class="preview" data-input-type="1"> 
      TEXT 
     </div> 
    </div> 
</div> 

更新

這似乎做什麼,我想......是在helper調用remove做的正確方法這個?

receive: function(event, ui) { 
    ui.helper.remove(); 
    var $this = $(this); 
    $.get("somewhere", function(data) { 
     // Note: presume more logic here..... 
     $($this).append(data); 
    }); 
} 

回答

1

這裏是一個解決方案的工作示例:

https://jsfiddle.net/Twisty/zh9szubf/

HTML

<div id="draggableItems"> 
    <div class="item"> 
    <div class="preview" data-input-type="1"> 
     TEXT 
    </div> 
    </div> 
</div> 

<ul id="desktoplayout"> 
    <li>Item 1</li> 
    <li>Item 2</li> 
    <li>Item 3</li> 
    <li>Item 4</li> 
</ul> 

JQuery的

$(function() { 
    $("#desktoplayout").sortable({ 
    receive: function(event, ui) { 
     var newItem; 
     $.post("/echo/html/", { 
     html: "<li class='newItem'>From Ajax</li>" 
     }, function(data) { 
     ui.helper.replaceWith(data); 
     }); 
    } 
    }); 

    var inputType; 

    $("#draggableItems .item").draggable({ 
    connectToSortable: "#desktoplayout", 
    helper: function (event) { 
     return "<div class='item'><img src='/Images/Header.png' /></div>"; 
    }, 
    start: function(event, ui) { 
     inputType = ui.helper.find('.preview').data("input-type"); 
    } 
    }); 
}); 

這也適用於$.get(),但是對於這個例子,它必須是$.post()。基本上,無論你想要的結果如何,該代碼應在ui.helper.replaceWith()部分。

+0

還更新以包含'inputType'數據:https://jsfiddle.net/Twisty/zh9szubf/4/ – Twisty

+0

更多的喜歡各種狀態:https://jsfiddle.net/Twisty/zh9szubf/5/ – Twisty

+0

更多的代碼清理,並抓住'TEXT'與盒本身時發現一個錯誤︰https://jsfiddle.net/Twisty/zh9szubf/6/ – Twisty