問題描述
在使用 jQuery UI 可拖動和可放置元素時,如何在放置時更改拖放元素?我正在嘗試將一個 DIV 拖到另一個可排序的 DIV.在放置時,我想更改放置的 DIV 上的類并更改其 innerHTML 內容.
When using jQuery UI draggables and droppables, how do you change the dragged-and-dropped element on drop? I am trying to drag one DIV to another sortable DIV. On drop, I'd like to change the classes on the dropped DIV and change its innerHTML content.
閱讀各種 StackOverflow 問題后,我的代碼如下所示:
After reading various StackOverflow questions, my code looks like this:
$(".column").droppable({
accept: '.element-dragging',
drop: function(event, ui) {
if ($(ui.draggable).hasClass("elemtxt")) {
$(ui.draggable).replaceWith('<div class="element element-txt">This text box has been added!</div>');
}
}
})
它不適合我.:-(
我的代碼的完整副本位于 http://www.marteki.com/jquery/bugkilling.php.
A full copy of my code is located at http://www.marteki.com/jquery/bugkilling.php.
推薦答案
從您提供的鏈接中獲取完整的 javascript 代碼,您可以進行如下更改以使其工作:
Taking the full javascript code from the link you gave, you can change it as follows to make it work:
$(function() {
$(".elementbar div").draggable({
connectToSortable: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
helper: 'clone',
revert: 'invalid'
});
$(".elementbar div, .elementbar div img").disableSelection();
$(".column").sortable({
connectWith: '.column',
cursor: 'move',
cursorAt: { top: 0, left: 0 },
placeholder: 'ui-sortable-placeholder',
tolerance: 'pointer',
stop: function(event, ui) {
if (ui.item.hasClass("elemtxt")) {
ui.item.replaceWith('<div class="element element-txt">This text box has been added!</div>');
}
}
});
$(".element").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all");
});
有幾個問題:
- drop 事件(您在問題中顯示的)沒有觸發,因為您沒有
接受
正確的內容. - 如果您同時擁有
.sortable
和.droppable
你最終會觸發奇怪的雙重事件.無論如何,這都是不必要的,因為您可以有效地從 sortable 的事件中獲取 drop 事件,因為您已將它與可拖動對象鏈接.
- The drop event (that you show in your question) wasn't firing because you weren't
accept
ing the right content. - If you have both
.sortable
&.droppable
you end up with weird double events firing. This is unnecessary anyway, since you can effectively grab the drop event from sortable's events given that you've linked it with the draggable.
還有一點需要注意 - 使用 sortable 的 receive
事件而不是 stop
會更好(因為每次任何排序停止和接收時都會觸發 stop當您將新項目放入排序列表時會特別觸發),但它無法正常工作,因為 item
尚未添加到可排序列表中,所以您沒有能夠在那個時候改變它.它在停止時可以正常工作,因為其他可排序項目都沒有 elemtxt
類.
One other thing to note - it would have been nicer to use the sortable's receive
event instead of stop
(since stop gets fired every time any sorting stops & receive is specifically there to fire when you drop a new item into the sort list), but it doesn't work properly because the item
hasn't yet been added to the sortable list, so you aren't able to change it at that point. It works ok on stop simply because none of the other sortable items have the elemtxt
class.
這篇關于使用 jQuery UI 拖放:更改拖放的元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!