如何使用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存在->做点什么?
答案 0 :(得分:0)
您可以使用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();
答案 1 :(得分:-1)
我认为您无法使用JQuery做到这一点。解决方案是添加任何您想做的事情,并将其添加到创建div的触发器中。用您正在描述的逻辑扩展当前功能。
发生了某些事情>创建了div>(如果在此声明[IF DIV EXISTS],请添加)
编辑: 或者,如果您确实需要它,可以尝试这样的事情:
$('mydiv').bind("DOMSubtreeModified",function(){
alert('changed');
});
如此处建议:jQuery Event : Detect changes to the html/text of a div