【问题标题】:Execute a function only when an element with a certain id becomes available仅当具有特定 id 的元素可用时才执行函数
【发布时间】:2020-12-17 21:23:24
【问题描述】:

我有一个 JavaScript 函数,只有当某个 id 的元素在 DOM 中可用时才应该执行该函数。

【问题讨论】:

  • 到目前为止您尝试了什么,但没有成功?
  • 没什么,我完全不知道从哪里开始。你见过 MutationObserver API 吗?还有比这更清晰的半烧古梵文手稿。
  • 选择是使用 MutationObserver 或 setInterval 持续检查元素

标签: javascript function listener observers


【解决方案1】:

按照文档生成工作示例并非易事,DOM documentation 可以提供有用的说明。

事实证明,MutationObserverInit dictionary 不是“对象类型”,而只是一个接口描述语言 (IDL) 术语,用于描述用于观察更改的选项对象 - 只需要一个 Object 对象。

FWIW 这是一个检测添加新节点或将现有节点的 id 更改为“certainId”的示例。

"use strict";
const target = document.getElementById("target");
const observer = new MutationObserver( checkChanges);
const certainId = "certainId";

function checkChanges(changeList, fromObserver) {
   console.log("Callback 2nd argument is the observer object: %s", fromObserver === observer);
   for( let change of changeList) {
      if( change.type == "attributes") {
          if( change.target.id === certainId) {
              console.log("id has been changed: ", change.target);
              break;
          }
      }
      else if( change.type == "childList") {
          for( let node of change.addedNodes) {
              if( node.id==certainId) {
                  console.log("target was added: ", node);
                  break;
              }
          }     
      }
   }
}
observer.observe( target, {
    subtree: true,
    attributeFilter: ["id"],
    childList: true
});

// test
function changeId() {
    if( document.getElementById("test1")) {
         test1.id = "certainId";
    }
}

function insertSpan() { // button click
    if( document.getElementById("test2")) {
       test2.innerHTML = '<span id="certainId">span#certainId<\/span>';
    }    
}
    
<div id="target">
    <div id="test1">
        div#test1 (oriinally)
    </div>
    <div id="test2">
       div#test2
    </div>
</div>
<button type="button" onclick='changeId()'>Set id value</button> OR
<button type="button" onclick="insertSpan()">insert new element</button>

可以单击 sn-p 中的两个测试按钮并生成具有重复 id 的元素 - 在实践中最好避免。

【讨论】:

    【解决方案2】:

    好吧,如果我正确理解您的需求,我相信这应该可行:

    const elementToObserve = document.querySelector("#parentElement");
    const lookingFor = '#someID';
    const observer = new MutationObserver(() => {
        if (document.querySelector(lookingFor)) {
            console.log(`${lookingFor} is ready`);
            observer.disconnect();
        }
    });
    
    observer.observe(elementToObserve, {subtree: true, childList: true});
    

    您将需要观察您希望元素出现的位置的父级。将 subtreechildList 选项设置为 true 时,它​​将观察那里的变化并在发现任何差异时触发回调。如果您要查找的元素现在在页面上,您可以签入该回调。

    【讨论】:

      猜你喜欢
      • 2012-10-21
      • 2022-11-28
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多