仅当具有特定ID的元素可用时才执行功能

时间:2020-08-29 00:22:12

标签: javascript function listener observers

我有一个JavaScript函数,只有当具有特定ID的元素在DOM中可用时才应执行。

2 个答案:

答案 0 :(得分:1)

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

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时,它将观察那里的更改,并在发现任何差异时触发回调。而且,您可以在该回调中签入要查找的元素是否在页面上。

答案 1 :(得分:1)

按照文档制作一个有效的示例并非易事,DOM documentation可以提供有用的说明。

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

FWIW这是一个示例,用于检测添加带有“ certainId”的新节点或将现有节点的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>

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