AJAX调用后访问DOM对象? [英] Accessing DOM object after AJAX call?
问题描述
我有一个典型的AJAX调用,将一些HTML附加到当前页面。我想要能够使用典型的jQuery选择器访问新插入的HTML。
I have a typical AJAX call that appends some HTML to the current page. I want to be able to access the newly inserted HTML with typical jQuery selectors.
这样我就可以像那样做。 ..
Here's what I'd like to be able to do...
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
}
});
$('#new_div').show();
#new_div
将是一些HTML元素我检索的数据。我不一定要将事件附加到新元素(如单击
),所以使用类似 .load()
或 .on()
不在这里(据我所知)。
#new_div
would be some HTML element from the data I retrieved. I don't necessarily want to attach events to the new elements (like click
), so using something like .load()
or .on()
doesn't work here (as far as I know).
我试过设置 $。ajax()
调用变量: var new_div = $ .ajax(...)
没有让我在任何地方。
I tried setting the $.ajax()
call to a variable: var new_div = $.ajax(...)
but that didn't get me anywhere.
推荐答案
如果您想在(甚至之前)插入之后立即操纵新内容它可以把DOM放在AJAX成功回调中:
If you would like to manipulate the new content immediately after (or even before) inserting it to the DOM, you can put that in the AJAX success callback too:
$.ajax({
url: url,
success: function(data) {
$('body').append(data);
$('#new_div').show();
}
});
另一方面,如果要将处理程序绑定到将添加到页面的内容ajax,jQuery这样做:
On the other hand, if you want to bind handlers to content that will be added to the page via ajax, jQuery does that like this:
$(document).on('click', '#new_div', function(){
alert("This function is bound to all #new_div's click events, even if they are added to the DOM via ajax later!")
});
这篇关于AJAX调用后访问DOM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!