将 JQuery 添加到使用 AJAX 加载的内容中
我刚刚了解到,您可以使用 live()
而不是 bind()
来确保使用 AJAX 重新加载内容后事件处理程序仍然存在...但是我能做什么与其他添加的 JQuery 一起使用吗,例如 .sortable()
?我有一个 UL,需要在排序或添加后重新加载;但是在AJAX重新加载之后,排序就不太正常了......
它并没有完全失去可排序性,但是拖动变得更加困难;它会跳来跳去,似乎会切换另外两个部分,而这两个部分不是我想要拖动的部分。这只发生在部分重新加载之后;我的猜测是,当它重新加载时,我需要重新附加可排序...我该怎么做?这是我的代码:
$("#sections").sortable({
start: function (event, ui) {
startIndex = ui.item.index();
},
update: function (event, ui) {
$.ajax({
type: "POST",
url: "/Form/sortSections",
data: {
formID: '@(Model.formID)',
displayOrder: ui.item.index() + 1,
sectionID: $(ui.item).attr("id"),
startDisplayOrder: startIndex + 1
},
success: function (result) {
$.get("/Form/_AllSections/@(Model.formID)", function (data) {
$("#sections").html(data);
});
},
error: function (req, status, error) {
alert(error);
}
});
}
});
I just learned that you can use live()
instead of bind()
to make sure an event handler still exists after content is reloaded with AJAX... but what can I do with other added JQuery, such as .sortable()
? I have a UL that I need to reload after sorting or adding; but after the AJAX reload, the sorting doesn't quite work right...
It doesn't completely lose the sortability, but the dragging become much more difficult; it will jump around and seemingly switch 2 other sections that's not the one I'm trying to drag. This only happens after the partial reload; my guess is that when it reloads, I need to re-attach the sortable... how can I do this? Here's my code:
$("#sections").sortable({
start: function (event, ui) {
startIndex = ui.item.index();
},
update: function (event, ui) {
$.ajax({
type: "POST",
url: "/Form/sortSections",
data: {
formID: '@(Model.formID)',
displayOrder: ui.item.index() + 1,
sectionID: $(ui.item).attr("id"),
startDisplayOrder: startIndex + 1
},
success: function (result) {
$.get("/Form/_AllSections/@(Model.formID)", function (data) {
$("#sections").html(data);
});
},
error: function (req, status, error) {
alert(error);
}
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
load
事件与live()
结合使用,以便每次将元素添加到 DOM 时都会运行该事件。http://api.jquery.com/load-event
Use the
load
event withlive()
so that it runs every time the element is added to the DOM.http://api.jquery.com/load-event