未捕获的TypeError:无法在"MutationObserver"上执行“观察":参数1的类型不是“节点" [英] Uncaught TypeError: Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'
问题描述
所以我下面的代码可以在jsfiddle中单独运行.但是出于某种奇怪的原因..在将其推送到实时服务器后我始终收到此错误:/,但我不知道为什么...
so my code below works stand alone in a jsfiddle. but for some odd reason.. I get this error consistently after pushing it to a live server :/ and I can't figure out why...
错误:
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定义以及目标的定义来解决此错误(元素)和配置变量:
I encountered the same error, and solved it by inserting the .observe() method under onload/ ready instead of the observer var definition, plus the definition of target(element) and config variables:
$(document).ready(function () {
var target = document.getElementById("myList");
var config = {
childList: true,
subtree: true,
attributes: true,
characterData: true
};
//note this observe method
observer.observe(target, config);
console.log("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>
请运行代码段,单击添加列表项"按钮,然后在控制台中查看更改日志.
Please run the code snippet, click the "Add list item" button and watch the change log in the console.
这篇关于未捕获的TypeError:无法在"MutationObserver"上执行“观察":参数1的类型不是“节点"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!