我有一个包含部分的 div:
<div class="Placeafterthis">
</div>
...
<div class="k-content">
<section class="rbs-section" id="id1" name="">
.. // section content
</section>
<section class="rbs-section" id="id2" name="">
.. // section content
</section>
<section class="rbs-section" id="id3" name="">
.. // section content
</section>
</div>
现在基本上这些部分是在 DOM 准备就绪时加载的。有什么方法可以检查特定部分何时完成加载?完成加载后,我需要克隆该部分并将其放置在“Placeafterthis”div 之后。关于如何实现这一点有什么建议吗?
最佳答案
您可以使用 MutationObserver
检测何时将节点添加到 .k-content
,clone它们使用 jQuery,并在 .Placeafterthis
( demo ) 之后附加它们:
var kContent = $('.k-content'); // the original container in which the items will be placed
var $Placeafterthis = $('.Placeafterthis'); // the cloned elements target marker placeholder
function mutationHandler(mutation) { // the mutation handler will deal with the addition of new nodes to the original container
var addedNodes = mutation.addedNodes;
if (!addedNodes.length) { // if no added nodes return
return;
}
$.each(addedNodes, function () { // iterate the add nodes
var $element = $(this);
if (!$element.hasClass('rbs-section')) { // if the node doesn't have the right class continue to the next one
return true;
}
var $prevSections = $Placeafterthis.find('~ .rbs-section'); // find if there are already sections append to the target
var $target = $prevSections.length === 0 ? $Placeafterthis : $prevSections.last(); // if there are sections take the last, if not use the marker
/** note that using .clone(true) will also clone all jQuery event handlers and data from the original element. If you don't need this behavior, just use .clone() **/
$target.after($element.clone(true)); // append after the target
});
}
var observer = new MutationObserver(function (mutations) { // create a new mutation observer
mutations.forEach(mutationHandler);
});
var config = { // config should include only childList because we just want added nodes
childList: true
};
observer.observe(kContent.get(0), config); // watch the original container with the observer
关于javascript - 在部分元素完成加载后捕获事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32395311/