использовать наблюдателя, чтобы определить, когда появляется элемент - PullRequest
0 голосов
/ 26 апреля 2018

Привет,

Я хочу получить текст из элемента, который не появится в DOM, пока пользователь не наведет курсор на другой элемент, поэтому я добавил наблюдателя, но все равно получаю сообщение об ошибке TypeError: document.getElementById(...) имеет значение null.

Это мой код:

document.addEventListener("DOMContentLoaded", function(event) {
// Select the node that will be observed for mutations
var parentOfMyList = document.body;

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            var lists = document.getElementById("list").textContent;
            console.log(lists)
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
observer.observe(parentOfMyList, config);   
});

Что я делаю не так?

Спасибо.

1 Ответ

0 голосов
/ 26 апреля 2018

Проверьте, существует ли элемент, прежде чем пытаться его использовать.

document.addEventListener("DOMContentLoaded", function(event) {
  // Select the node that will be observed for mutations
  var parentOfMyList = document.body;

  // Options for the observer (which mutations to observe)
  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };

  // Callback function to execute when mutations are observed
  var callback = function(mutationsList) {
    for (var mutation of mutationsList) {
      if (mutation.type == 'childList') {
        var elt = document.getElementById("list");
        if (elt) {
          var lists = elt.textContent;
          alert(lists);
        }
      }
    }
  };

  // Create an observer instance linked to the callback function
  var observer = new MutationObserver(callback);
  observer.observe(parentOfMyList, config);

  var container = document.querySelector("#container");
  document.querySelector("#b1").addEventListener("click", function() {
    var l = document.createElement("div");
    l.id = "list";
    l.textContent = "This is the list";
    container.appendChild(l);
  });

  document.querySelector("#b2").addEventListener("click", function() {
    var l = document.createElement("div");
    l.id = "list2";
    l.textContent = "This is list #2";
    container.appendChild(l);
  });
});
#container {
  height: 50px;
  width: 100%;
  background-color: yellow;
}

#list1 {
  background-color: green;
}

#list2 {
  background-color: pink;
}
<div id="container"></div>
<button id="b1">Click to create list</button>
<br>
<button id="b2">Click to create list2</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...