未捕获的类型错误:无法执行'观察'在'突变观察者':参数1不是'节点'

Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'

本文关键字:观察者 突变 参数 节点 不是 观察 错误 类型 执行      更新时间:2023-09-26

所以我下面的代码在jsfiddle中单独工作。但出于某种奇怪的原因。。在将其推送到实时服务器后,我一直会收到这个错误:/我不明白为什么。。。

错误

mycodewitherror.js:23 Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

js:


$(document).ready(function() {
// The below collects user login name, new login date and time, and previous use URL
var element = document.querySelector('.pet-name'); 
// create an observer instance
var observer = new MutationObserver(function(mutations) {
      var username = $('.pet-name').text();
      var referrer = document.referrer;
      var date = new Date();
      var month = date.getUTCMonth() + 1;
      var day = date.getUTCDate();
      var year = date.getUTCFullYear();
      var time = date.toLocaleTimeString();
      var formattedDate = month + '/' + day + '/' + year;
    console.log("Pet Name Time"); 
      console.log(referrer); 
      console.log(petname); 
      console.log(time); 
      console.log(formattedDate);   
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(element, config);

我遇到了同样的错误,并通过在onload/ready代码块内调用.observe()方法而不是观测器var定义,再加上target元素和config变量的定义来解决它:

请运行下面的代码片段,单击";添加列表项";按钮,并在控制台中查看更改日志。

$(document).ready(function () {
    var target = document.getElementById("myList");
    var config = {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    };
    //note this observe method call
    observer.observe(target, config);
    console.log("Observer is registered");
});
var observer = new MutationObserver(function (mutationRecords, observer) {
    mutationRecords.forEach(function (mutation) {
        console.log("mutation change in ", mutation.type, " name: ",mutation.target);
    });
});
function add() {
    var index = $("ul li").length;
    var listItem = document.createElement("li");
    listItem.textContent = index + 1;
    var target = document.getElementById("myList").appendChild(listItem, "before");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body >
    <button onclick="add()">Add list item</button>
    <hr>
    <ul id="myList">
        <li><a href="#">1</a></li>
        <li><a href="#">2</a></li>
    </ul>
    
</body>