更新: 興味のある人のために、私が最終的に使用した実装を次に示します。
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
それが誰かに役立つことを願っています。
注:ダリルの答えではなく、この解決策にたどり着いた理由は、同じドキュメント内にいる場合にのみ getElementById 手法が機能するためです。ページにいくつかのiframeがあり、ページは複雑な方法で相互に通信します-これを試したとき、実行中のコードとは異なるドキュメントの一部であるため、要素が見つからないという問題がありました.