繁体   English   中英

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

[英]How to check if element is already loaded via AJAX?

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

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设置为同步,因为默认情况下它是异步的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM