AJAX 调用后 jQuery 绑定点击链接
我很生气——也许有人能帮我解决这个问题。
我需要在 AJAX 调用后将点击重新绑定到链接,但由于某种原因它不想工作。
这是我的代码:
if ($('.active').length > 0) {
$('.active').click(function() {
var elem = $(this);
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
elem.replaceWith(data);
}
});
$('.active').bind('click'); return false;
});
}
有什么想法吗?
感谢您的回复 - 我已经修改了代码,但问题仍然存在:
function makeActive() {
if ($('.active').length > 0) {
$('.active').click(function() {
var elem = $(this);
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
elem.replaceWith(data);
}
});
$('.active').live('click', makeActive);
return false;
});
}
}
$('.active').live('click', makeActive);
I'm getting furious - perhaps someone will be able to help me with this.
I need to re-bind the click to the link after AJAX call, but for some reason it doesn't want to work.
Here's my code:
if ($('.active').length > 0) {
$('.active').click(function() {
var elem = $(this);
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
elem.replaceWith(data);
}
});
$('.active').bind('click'); return false;
});
}
Any idea?
Thanks for the responses - I've amended the code, but the problem is still there:
function makeActive() {
if ($('.active').length > 0) {
$('.active').click(function() {
var elem = $(this);
var url = $(this).attr('href');
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
elem.replaceWith(data);
}
});
$('.active').live('click', makeActive);
return false;
});
}
}
$('.active').live('click', makeActive);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新于 2012 年 10 月 31 日
从 jQuery 1.7 开始,推荐的方法是使用
on
-你能尝试以下操作吗?
UPDATE on October 31, 2012
Starting from jQuery 1.7, the recommended approach is to use
on
-Can you try the following ?
如果您想在 Ajax 调用之后执行它,则必须在
success
处理程序中添加重新绑定:也就是说,在本例中,
live()
或delegate()
可能是更好的选择 [更新:既然 jQuery 1.7 已经出来了,一切都可以用.on()
]。如果您还有其他未替换的.active
链接,这还可以防止点击处理程序的双重分配。更新:关于您更新的代码:您使用
live
的方式违背了其目的。请阅读其文档。您所做的是在单击链接时分配一个单击处理程序,这意味着您要一遍又一遍地添加单击处理程序。这是您的代码的改进版本。
You would have to add the rebinding in the
success
handler if you want to execute it after the Ajax call:That said, in this case,
live()
ordelegate()
are probably better options [update: now that jQuery 1.7 is out, everything can be done with.on()
]. This would also prevent double assignment of click handlers, in case you have other.active
links that have not been replaced.Update: Regarding your updated code: The way you are using
live
defeats its purpose. Please read its documentation. What you are doing is assigning a click handler when the the link is clicked, which means that you are adding click handlers over and over again.This is an improved version of your code.