jQuery 适用于 DOM 元素。这些方法大多在文档准备好后运行(在所谓的 $(document),ready() 方法中)。因此,在 ajax 调用之前初始化的方法将无法访问动态创建的元素。为此,您可以在completeajax 调用的方法中再次初始化 bind 方法。下面是一个例子:
示例 1:这行不通。
HTML
<ul>
    <li>item</li>
    <li>item</li>
    <li>item</li>
</ul>
<button onclick="get_ajax_data();">Get Data</button>
jQuery
$(document).ready(function(){
    get_width();
    get_ajax_data();
});
function get_width(){
    # some code to get the width;
}
function get_ajax_data(){
    $.ajax({
        # Some code to get data from the ajax call
        # and then append it as a <li> to the <ul>
    });
}
在上面的示例中,如果您单击按钮获取数据,则get_width方法将无法访问<li>通过 ajax(动态)添加的新项目,因为在get_width初始化方法时该<li>元素不存在。因此,您需要按以下方式进行操作。
示例 2:这可行。
HTML
<ul>
    <li>item</li>
    <li>item</li>
    <li>item</li>
</ul>
<button onclick="get_ajax_data();">Get Data</button>
jQuery
$(document).ready(function(){
    get_ajax_data();
});
function get_width(){
    # some code to get the width;
}
function get_ajax_data(){
    $.ajax({
        # Some code to get data from the ajax call
        # and then append it as a <li> to the <ul>
        complete: function(){
            get_width();
        }
    });
}
在上面我们所做的是get_width在我们的 ajax 调用完成后再次初始化该方法,以便get_width也可以访问新创建的元素。