将节点添加到 DOM 时使用react的 jQuery 事件(或 hack)

标签 jquery dom

我希望在将元素添加到 DOM 时触发一个事件。我们可以直观地思考一下:

//pick the generic selector of your choice.
//The naive idea is to execute this handler when an element satisfying
//  this selector is added to the DOM.
$('my-tag.my-class:my-pseudo-selector').ready(function() {
    // do initialization for element
});

但这不起作用。这也不会:

$(document).on('ready', 'my-tag.my-selector:my-pseudo-selector', function() {
    // do initialization for every element added to the dom, now and in the future
});

.ready is only intended to work with document .

当稍后将元素添加到 dom 时,如何才能触发行为(或 hack)?此添加将由异步 javascript 通过以下三种方式之一执行:

  • Ajax .js 响应。
  • 用于 ajax 响应的 JS 处理程序。
  • 调用 .html('<my-tag class="my-class" />') ,或调用 insertBefore , insertAfter , appendTo , append ,...以及类似的调用。

最佳答案

尝试https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

这是一个例子:

var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']};
var mutationObserver = new MutationObserver(function(mutationRecords) {
  $.each(mutationRecords, function(index, mutationRecord) {
    if (mutationRecord.type === 'childList') {
      if (mutationRecord.addedNodes.length > 0) {
        //DOM node added, do something
      }
      else if (mutationRecord.removedNodes.length > 0) {
        //DOM node removed, do something
      }
    }
    else if (mutationRecord.type === 'attributes') {
      if (mutationRecord.attributeName === 'class') {
        //class changed, do something
      }
    }
  });
});
mutationObserver.observe(document.body, whatToObserve);

关于将节点添加到 DOM 时使用react的 jQuery 事件(或 hack),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585426/

相关文章:

javascript - 通过javascript、ajax发送到服务器的base64代码

javascript - 在 Chrome 下 - Mootools 注入(inject)因 null 元素而失败

jquery - 如何获取带有类名的内部div的值?

javascript - 如何在 JavaScript 中将 addEventListener 指定为 ON?

javascript - js如何在使用文件:///protocol时动态加载json文件

tabs - 如何在文本框中按 Tab 键后触发事件

php - Simplexml XPath 异常

javascript - 如何在 HTML 和 JavaScript 中检测用户是否选择了整个文档?

javascript - 当我的窗口宽度小于 800px 时,如何将 js slider 效果更改为淡入淡出?

javascript - 声音管理器 2 : All buttons working except for 'Play' when streaming from Soundcloud