jQuery中使用AJAX加载链接后获取href值
我正在尝试使用 AJAX 更新数据库中的单个记录。一切都工作正常,但是当结果返回时,它看起来很好,但是如果再次单击 a.update (对于返回的元素),我会打开 href (所以第二次 attr() 对某些情况不起作用原因)。我对 jQuery 和 ajax 非常陌生:)
// Update Single Item
$('li a.update').click(function () {
updateURL = $(this).attr("href");
$(this).attr("href", "#");
theContainer = $(this).parents('li');
$.ajax({
type: "GET",
dataType: 'json',
url: updateURL,
async: false,
success: function(data){
theContainer.replaceWith(data.html).fadeIn(300);
}
});
return false;
});
ps List 元素是用 PHP 生成的。当我请求单个
元素时,我使用完全相同的模板生成它(默认情况下,所有内容都使用 foreach 循环打印,之后 AJAX 请求返回一个带有 <; 的 JSON)。 li>...
I am trying to update a single record in my database with AJAX. Everything is working fine, but when the result is returned, it looks fine, but if a.update is clicked again (for the returned element) I get the href opened (so the second time the attr() doesn't work for some reason). I am very new to jQuery and ajax :)
// Update Single Item
$('li a.update').click(function () {
updateURL = $(this).attr("href");
$(this).attr("href", "#");
theContainer = $(this).parents('li');
$.ajax({
type: "GET",
dataType: 'json',
url: updateURL,
async: false,
success: function(data){
theContainer.replaceWith(data.html).fadeIn(300);
}
});
return false;
});
p.s. The List element is generated with PHP. When I request a single <li>
element, I generate it with the exact same template (by default everything is printed with a foreach loop, afterwards AJAX requests get back a JSON with <li>...</li>
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
live
方法将事件侦听器附加到所有匹配的元素,无论它们是否已经在 DOM 中:附加事件侦听器的方式只会将其附加到当前位于的元素DOM,并且当您通过 AJAX 添加新的 DOM 时,它们不会接收事件侦听器。
You can use the
live
method to attach the event listener to all matching elements regardless of whether they are already in the DOM or not:The way you are attaching the event listener will only attach it to elements currently in the DOM, and as you are adding new ones via AJAX, they don't receive the event listener.