观看 HTML 并执行 jQuery 脚本



我怎样才能用jQuery不断观察HTML,当div存在时,执行一些东西。

我已经有了这个:

if ( $( "#works_to_perform_div span.help-block.error-help-block" ).length ) {
$('#works_to_perform_div span.help-block.error-help-block').appendTo('#works_to_perform_div .question__label');
}

但这不起作用,因为div 如果在不刷新的情况下被推到屏幕上。

是不是有一些像 观看div ->如果div 存在 ->做某事?

您可以使用 MutationObserver

来自 mdn 的示例

// Select the node that will be observed for mutations 
var targetNode = document.getElementById('some-id'); // Options for the observer (which mutations to observe) 
var config = {
attributes: true,
childList: true,
subtree: true
}; // Callback function to execute when mutations are observed 
var callback = function(mutationsList, observer) {
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
}; // Create an observer instance linked to the callback function 
var observer = new MutationObserver(callback); // Start observing the target node for configured mutations 
observer.observe(targetNode, config); // Later, you can stop observing 
observer.disconnect();

我认为你不能用JQuery做到这一点。解决方案是添加您想要执行的任何操作,并将其添加到创建div 的触发器中。使用所描述的逻辑扩展当前函数。

创建div>>发生某些事情(在此处添加 if 语句 [如果div 存在]( 做点什么

编辑: 或者,如果您确实需要,您可以尝试这样的事情:

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

如此处建议:jQuery 事件:检测对div 的 html/文本的更改

最新更新