所以我使用Jquery UI和Jquery构建了自己的拖放购物车(非常基本)。现在的功能就是这样 - 将元素拖到“在此处添加项目”并附加它们。将打开一个模态窗口,允许您编辑项目的名称。当您添加两个或多个项目时,会出现此问题,您为当前元素设置的名称将替换为您添加的所有三个项目。在我看来,这种循环?
这是完整代码的链接。 http://jsbin.com/egosi4/2
此时的任何帮助都非常感谢。谢谢。
答案 0 :(得分:2)
你不应该在可重新调用函数中放置change()和click()事件,因为每次调用change()和click()时,它都会向事件注册一个函数,这就是你看到的循环
我尝试编辑您的脚本并使用data()函数将id传递给事件。 (我已删除你的提醒())
这里的演示 http://jsfiddle.net/42gAn/
完整代码
$(function() {
//Draggable element events
$( "#catalog li" ).draggable({
appendTo: "body",
helper: "clone"
});
//---------------------------------
//Function to generate a unique ID
var generateuniqueid = function(id){
unique_id="element"+id;
return unique_id;
}
//---------------------------------
//function to get content from user - MODAL DIALOG
var fillcontent = function(id,content){
//Open up lightbox
$( "#box:ui-dialog" ).dialog( "destroy" );
$( "#box" ).dialog({
height: 140,
modal: true
});
//var id='#'+id;
$("input.thecontent").data("id",id);
}
$("input.thecontent").change(function(){
var id='#'+ $("input.thecontent").data("id");
var usercontent = $("input.thecontent").val();
$(id).text(usercontent);
});
$( ".closemodal" ).click(function() {
closemodal();
//id=null;
});
//Flush the ID
//---------------------------------
var closemodal=function(){
$( "#box" ).dialog("close");
}
//---------------------------------
//---------------------------------
//Declare the ID to start incrementing from
universal_id=1;
//---------------------------------
$( "#cart div" ).droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function( event, ui ) {
$( this ).find( ".placeholder" ).remove();
//Generate unique id
unique_id=generateuniqueid(universal_id);
$( "<div></div>" ).html(ui.draggable.html()).appendTo( this ).attr('id', unique_id).attr('class', 'rmg');
//Get the Content from user and fill it up
//unique_id="#"+unique_id;
inputcontent=fillcontent(unique_id,'Empty');
universal_id++;
unique_id=null;
}
}).sortable({
items: "div:not(.placeholder)",
sort: function() {
$( ".rmg" ).dblclick(function() {
var theid=$(this).attr('id');
var content=$(this).text();
fillcontent(theid,content);
});
// gets added unintentionally by droppable interacting with sortable
// using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options
//$( this ).removeClass( "ui-state-default" );
}
});
});