代码之家  ›  专栏  ›  技术社区  ›  Lieutenant Dan

在div中显示内容更改的日期和时间(vanilla js)

  •  0
  • Lieutenant Dan  · 技术社区  · 7 年前

    我试图使用vanilla js;显示更新html元素的日期和时间。

    例如,当内容在My中更改时:

    <li class="active"></li>
    

    我知道jquery有通过选择器快速识别的方法,即。

    $('li.active').bind("DOMSubtreeModified",function(){
        alert('changed');
    });
    

    但我需要一个普通的js解决方案。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Get Off My Lawn    7 年前

    使用变异观察者来观察列表项,而不是整个文档。

    // The item we want to watch
    var watch = document.querySelector('.active')
    
    // The new observer with a callback to execute upon change
    var observer = new MutationObserver((mutationsList) => {
      console.log(new Date().toUTCString())
    });
    
    // Start observing the element using these settings
    observer.observe(watch, { childList: true, subtree: true });
    
    // Some random test function to modify the element
    // This will make sure the callback is running correctly
    setInterval(() => {
      watch.innerHTML = Math.random() * 1000
    }, 1000)
    <ul>
      <li class="active"></li>
    </ul>
        2
  •  -2
  •   Christoph Herold    7 年前

    大多数jquery代码都有类似的对应代码。这个 $('li.active') 可替换为 document.querySelectorAll('li.active') 是的。这将为您提供与选择器匹配的所有元素。这个 bind 通过迭代元素并使用 addEventListener('DOMSubtreeModified', function(event) { … }) 是的。