更新:对于任何对此感兴趣的人,这是我最终使用的实现:
function isInDOMTree(node) {
// If the farthest-back ancestor of our node has a "body"
// property (that node would be the document itself),
// we assume it is in the page's DOM tree.
return !!(findUltimateAncestor(node).body);
}
function findUltimateAncestor(node) {
// Walk up the DOM tree until we are at the top (parentNode
// will return null at that point).
// NOTE: this will return the same node that was passed in
// if it has no ancestors.
var ancestor = node;
while(ancestor.parentNode) {
ancestor = ancestor.parentNode;
}
return ancestor;
}
我想要这样做的原因是提供一种onload
为 DOM 元素合成事件的方法。这是那个函数(虽然我使用的东西略有不同,因为我将它与MochiKit结合使用):
function executeOnLoad(node, func) {
// This function will check, every tenth of a second, to see if
// our element is a part of the DOM tree - as soon as we know
// that it is, we execute the provided function.
if(isInDOMTree(node)) {
func();
} else {
setTimeout(function() { executeOnLoad(node, func); }, 100);
}
}
例如,可以按如下方式使用此设置:
var mySpan = document.createElement("span");
mySpan.innerHTML = "Hello world!";
executeOnLoad(mySpan, function(node) {
alert('Added to DOM tree. ' + node.innerHTML);
});
// now, at some point later in code, this
// node would be appended to the document
document.body.appendChild(mySpan);
// sometime after this is executed, but no more than 100 ms after,
// the anonymous function I passed to executeOnLoad() would execute
希望这对某人有用。
注意:我最终选择此解决方案而不是Darryl 的答案的原因是 getElementById 技术仅在您位于同一文档中时才有效;我在页面上有一些 iframe,页面之间以一些复杂的方式相互通信 - 当我尝试这个时,问题是它找不到元素,因为它是与它正在执行的代码不同的文档的一部分.