Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否为新创建的元素指定一个观察者?_Javascript_Dom_Styles_Mutation Observers - Fatal编程技术网

Javascript 是否为新创建的元素指定一个观察者?

Javascript 是否为新创建的元素指定一个观察者?,javascript,dom,styles,mutation-observers,Javascript,Dom,Styles,Mutation Observers,如何为新创建的元素创建一个观察者?当我创建新元素时,mutationobserver不起作用。我需要注册这个巨大的盒子是否改变了风格 <button onclick="myFunction()">Create</button> <button onclick="myFunctionStyle()">Change style</button> 由于新添加的元素被附加到document.body,因此您需要将另

如何为新创建的元素创建一个观察者?当我创建新元素时,mutationobserver不起作用。我需要注册这个巨大的盒子是否改变了风格

<button onclick="myFunction()">Create</button>
<button onclick="myFunctionStyle()">Change style</button>

由于新添加的元素被附加到
document.body
,因此您需要将另一个MutationObserver附加到该元素

new MutationObserver(() => {
  console.log('mutation on document body');
  // rest of the code you need when an element is appended
})
  .observe(document.body, { childList: true })

一切都正常工作,但如果创建了一个新元素,则简单地说,mutationObserver不会注册它。如果该元素从未附加,则检测它的唯一方法是覆盖并修补
文档
上的
createElement
方法。如果您不知道它将被附加到哪里,但它将被附加到某个地方,那么您可以这样做,或者附加一个递归观察者,除了childList prop之外,它还带有
子树:true
。在本例中,我在document.body中指定了create元素,但在其他创建的元素中需要它。Div-inside-Div…,inside-Div…,我正在尝试您的解释,但它不起作用。最好的解决方案是识别您感兴趣的每个容器,并在每个容器上附加一个观察者,带有
childList:true
。我理解您的意思,但每个父容器都是被创建的…,所以。。。陛下
new MutationObserver(() => {
  console.log('mutation on document body');
  // rest of the code you need when an element is appended
})
  .observe(document.body, { childList: true })