gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:46:35 25 4
gpt4 key购买 nike

我希望在将元素添加到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com