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 :)
我试图用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;
});
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>
)
附: List元素是使用PHP生成的。当我请求单个
1 个解决方案
#1
1
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:
您可以使用live方法将事件侦听器附加到所有匹配的元素,无论它们是否已存在于DOM中:
$('li a.update').live("click", function() {
//Your code
});
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.
附加事件侦听器的方式只会将它附加到当前DOM中的元素,而当您通过AJAX添加新元素时,它们不会收到事件侦听器。
#1
1
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:
您可以使用live方法将事件侦听器附加到所有匹配的元素,无论它们是否已存在于DOM中:
$('li a.update').live("click", function() {
//Your code
});
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.
附加事件侦听器的方式只会将它附加到当前DOM中的元素,而当您通过AJAX添加新元素时,它们不会收到事件侦听器。