我想要的是
我正在使用 AJAX 从服务器端加载 HTML 片段,并将其附加到文档中,并且我想要一种在片段完全添加到 dom 时得到通知的方法。
我正在做这样的事情:
// Load photos.html from the server with ajax
var instance = loadPageWithAjax('photos.html')
// Wait for response
instance.success = function(response){
// Create Parent Object
// Note that I MUST create a new div in my project
var box = document.createElement('div');
box.id = 'photos-box';
// Insert html response to the box's innerHTML
box.innerHTML = response;
// Append box to the dom
document.body.appendChild(box);
}
当片段添加到 dom 时,我想使用其中的内容,但我不能,因为我不知道片段何时实际添加到 dom 中。
我试过的
我试图在响应后附加一个脚本:
document.getElementById('photo-box') = response
+ '<script>alert(\'loaded\')</script>';
它已添加但不作为脚本加载我真的不知道为什么?
然后我尝试将其附加为部分有效的新对象:
var script = document.createElement('script');
script.type = 'text/javascript';
script.innerHTML = 'alert(\'loaded\')';
document.getElementById('photo-box').appendChild(script);
但它比片段的其他部分加载速度更快。
那么当片段被添加到 dom 时获得通知的正确方法是什么?