所以我的代码在jsfiddle中独立工作.但由于一些奇怪的原因..我把它推到现场服务器后一直得到这个错误:/我无法弄清楚为什么……
错误:
mycodewitherror.js:23 Uncaught TypeError: @R_502_159@ 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(element)和config变量的定义来解决它:
$(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>