附加到 DOM 的 jQuery 新元素不起作用
我有一个可以选择并拖动多个元素的脚本。它工作正常,但是当我想向该函数添加另一个新元素,将其附加到 DOM 时,它不起作用。功能是:
$(function() {
var selected = $([]), offset = {top:0, left:0};
$("#selectable1").selectable();
$("#selectable1 span").draggable({
start: function(ev, ui) {
$(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");
$("span").removeClass("cica"); // ads class Cica to the draged/selected element
$(this).addClass("cica");
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
$(this).text("Selected and dragging object(s)");
});
offset = $(this).offset();
},
drag: function(ev, ui) {
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function() {
var el = $(this), off = el.data("offset");
el.css({top: off.top + dt, left: off.left + dl});
});
},
stop: function(ev, ui){
$(this).text("Drag has stopped");
}
});
});
新元素的添加方式如下:
$('<span class="drag">Xia</span>').appendTo('#selectable1');
我知道我可以使用 live 使其工作,但我不知道在脚本中的何处添加它。我只知道如何将其添加到单击、鼠标悬停等事件上。
如果您对此有任何建议,请告诉我。
谢谢
I have a script that selects and drags several elements. It works fine but when I want to add another new element to that function, append it to DOM, it does not work. The function is:
$(function() {
var selected = $([]), offset = {top:0, left:0};
$("#selectable1").selectable();
$("#selectable1 span").draggable({
start: function(ev, ui) {
$(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");
$("span").removeClass("cica"); // ads class Cica to the draged/selected element
$(this).addClass("cica");
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
$(this).text("Selected and dragging object(s)");
});
offset = $(this).offset();
},
drag: function(ev, ui) {
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function() {
var el = $(this), off = el.data("offset");
el.css({top: off.top + dt, left: off.left + dl});
});
},
stop: function(ev, ui){
$(this).text("Drag has stopped");
}
});
});
The new element is added like this:
$('<span class="drag">Xia</span>').appendTo('#selectable1');
I know that I can use live to make it work but I do not know where to add it in the script. I only know how to add it on a event like click, mouseover.
Please let me know if you have some tips on this one.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我要做的就是为名为“dragSetup”的虚构事件设置一个事件处理程序“#selectables1”。看起来像这样:
然后每当您添加新的时,您都可以调用:
What I'd do is to set up "#selectables1" with an event handler for a made-up event called "dragSetup". That would look something like this:
Then whenever you add a new you can just call:
您必须使用
live
将事件附加到加载 DOM 后添加的 DOM 元素。 实时 jQuery 文档You have to use
live
to attach the events to the DOM elements that are added once the DOM is loaded. jQuery Doc for live