You need to enable JavaScript to run this app. 为什么MutationObserver回调参数是MutationRecord数组?求多记录触发示例
优惠活动
大模型
产品
解决方案
定价
更多

为什么MutationObserver回调参数是MutationRecord数组?求多记录触发示例

为什么MutationObserver回调参数是数组

MutationObserver采用异步批量触发的设计,不会在每次DOM发生变更时立刻执行回调,而是会将当前微任务周期内所有符合监听规则的DOM变更都收集起来,攒成MutationRecord数组后一次性触发回调,避免频繁触发回调导致的性能损耗,这就是回调参数为数组的核心原因。

官方对该参数的说明如下:

由MutationRecord对象组成的数组,描述每一次发生的变更;

可触发mutationRecordList.length > 1的示例

你原有的代码每次点击只触发1次符合规则的DOM变更,因此每次回调拿到的数组长度都是1。只需要在同一次同步执行流程中触发多次符合监听规则的DOM变更,就能拿到长度大于1的记录数组,修改后的代码如下:

<h2 id="testNode" onclick="addTimeNode(this)">Click me!</h2>

<script>
  function addTimeNode(node) {
    // 变更1:修改节点自定义属性
    node.dataset.clickCount = Number(node.dataset.clickCount || 0) + 1
    // 变更2:修改节点文本内容
    node.firstChild.textContent = `已点击${node.dataset.clickCount}次,点击继续`
    // 变更3:新增第一个p节点
    const nodeP1 = document.createElement("p")
    const today = new Date()
    nodeP1.innerText = [today.getHours(), today.getMinutes(), today.getSeconds()].join(":")
    node.append(nodeP1)
    // 变更4:新增第二个p节点
    const nodeP2 = document.createElement("p")
    nodeP2.innerText = "额外新增的节点"
    node.append(nodeP2)
  }

  (
    () => {
      window.onload = () => {
        const observer = new MutationObserver((mutationRecordList, observer)=>{
          if (mutationRecordList.length > 1){
            console.log("Thanks. This is what I want!") // 👈 点击后会触发该日志打印
          }
          console.log(observer.name)
          for(const mutation of mutationRecordList) {
            const target = mutation.target
            switch(mutation.type) {
              case "childList":
                console.log('A child node has been added or removed.')
                break
              case "attributes":
                console.log('Attribute of node has been changed.')
                break
              case "characterData":
                console.log('Text content of node has been changed.')
                break
            }
            if (target.childNodes.length > 2) {
              observer.disconnect()
              console.log('disconnect observer')
            }
          }
        })
        observer.name = "test observer"
        observer.observe(document.getElementById('testNode'), {
          childList: true,
          attributes: true,
          characterData: true,
          subtree: true
        })
      }
    }
  )()
</script>

运行上述代码后点击页面上的h2节点,就能触发你预期的日志打印。

内容的提问来源于stack exchange,提问作者Carson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 08:45:02