简体   繁体   English

使用观察者来检测元素何时出现

[英]use observer to detect when an element appears

Hi, 你好

I want to get the text from an element that wont appear in the DOM until the user hovers another element so I added an observer but I still get an error that says TypeError: document.getElementById(...) is null. 我想从元素中获取文本,直到用户将鼠标悬停在另一个元素上,该元素才会出现在DOM中,所以我添加了一个观察者,但仍然收到一个错误,提示TypeError:document.getElementById(...)为null。

This is my code: 这是我的代码:

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

What am I doing wrong? 我究竟做错了什么?

Thank you. 谢谢。

Check whether the element exists before trying to use it. 尝试使用该元素之前,请检查其是否存在。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM