【问题标题】:how do you trigger a function when more content is loaded onto a page, like tumblr and infinite scroll当更多内容加载到页面上时,您如何触发功能,例如 tumblr 和无限滚动
【发布时间】:2014-07-06 19:59:50
【问题描述】:

您好,我正在编写一个谷歌浏览器扩展程序,为一个项目重新设计 tumblr,

我正在尝试删除注释数量之后的“注释”。

到目前为止,我已经使用了这个,除了 tumblr 会在您向下滚动时加载更多帖子并且这些帖子不会受到影响...:/

每次加载更多帖子或其他方式时,我将如何触发此功能?

$('.note_link_current').each( function(index) {
  // Inside this function, "this" refers to the (DOM) element selected
  var text = $(this).text();
  /* ... */
});

任何帮助将不胜感激......

【问题讨论】:

    标签: javascript google-chrome-extension


    【解决方案1】:

    您想要的是在插入到按类过滤的 DOM 中的每个节点上运行一些代码。

    这样做的现代方法是使用 DOM MutationObserver。这是关于它的canonical answer,这是关于它的good documentation

    简而言之,您应该这样做:

    function handleNote(element){
      var text = $(element).text();
      /* ... */
    }
    
    // Initial replacement
    $('.note_link_current').each( function(index) { handleNote(this); });
    
    var observer = new MutationObserver( function (mutations) {
      mutations.forEach( function (mutation) {
        // Here, added nodes for each mutation event are in mutation.addedNodes
        $(mutation.addedNodes).filter('.note_link_current').each(
          function(index) { handleNote(this); }
        );
      });
    });
    
    // Watch for all subtree modifications to catch new nodes
    observer.observe(document, { subtree: true, childList: true });
    

    【讨论】:

    • 这对我不起作用:/ 我在滚动时收到突变警报,但不仅仅是在加载新内容时...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多