如何检查元素是否已经通过AJAX加载

How to check if element is already loaded via AJAX?

本文关键字:加载 AJAX 是否 元素 何检查 检查      更新时间:2024-04-13

我想检查元素是否已经加载。

HTML

<button>load</button>

JS-

$(document).on('click','button',function () {
    $.ajax({
        url: 'additional.html',
        context: document.body,
    }).done(function(html) {
        $('body').append(html);
    });
});
//My incorrect suggestion
if ($('input').is(':visible')) {
    alert('I see loaded element!');
}

我可以将警报移动到.done()块,,但我不允许更改它。那么,当元素出现时,我应该为if语句使用什么事件侦听器来显示alert呢?

您可以这样做:

$('body').bind("loaded", function () {
    alert('I see loaded element!');
});
$(document).on('click','button',function () {
  $.ajax({
    url: 'additional.html',
    context: document.body,
  }).done(function(html) {
    $('body').append(html);
    $('body').trigger("loaded");
  });
});

或者,您可以将jquery-ajax设置为sync,因为默认情况下它是异步的。