如何确定动态创建的 DOM 元素是否已添加到 DOM 中?

2024-04-28

根据规格 http://www.w3.org/TR/REC-html40/interact/scripts.html, 只有BODY and FRAMESETelements 提供了一个要附加的“onload”事件,但我想知道动态创建的 DOM 元素何时被添加到 JavaScript 中的 DOM 中。

我目前使用的非常简单的启发式方法(有效)如下:

  • 遍历父节点元素的属性返回,直到找到最终祖先(即parentNode.parentNode.parentNode.etc,直到parentNode为空)

  • If the ultimate ancestor has a defined, non-null body property

    • 假设相关元素是 dom 的一部分
  • else

    • 100 毫秒内再次重复这些步骤

我所追求的要么是确认我所做的事情是足够的(同样,它在 IE7 和 FF3 中都有效),要么是一个更好的解决方案,无论出于何种原因,我完全没有注意到;也许我应该检查其他属性等等。


编辑:我想要一种与浏览器无关的方式来执行此操作,不幸的是,我并不生活在一个浏览器的世界中;也就是说,我们欢迎特定于浏览器的信息,但请注意您所知道的浏览器does工作。谢谢!


更新:对于任何对此感兴趣的人,这是我最终使用的实现:

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;
}

我想要这个的原因是提供一种合成方法onloadDOM 元素的事件。这是该函数(尽管我使用的函数略有不同,因为我将它与MochiKit http://www.mochikit.com/):

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

希望这对某人有用。

注意:我最终选择这个解决方案而不是达里尔的回答 https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224是因为 getElementById 技术仅在您位于同一文档中时才有效;我在页面上有一些 iframe,并且页面以一些复杂的方式在彼此之间进行通信 - 当我尝试此操作时,问题是它找不到该元素,因为它是与其执行的代码不同的文档的一部分。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何确定动态创建的 DOM 元素是否已添加到 DOM 中? 的相关文章

随机推荐