在section元素加载完成后捕获事件

Neo*_*ile 13 html javascript jquery kendo-ui

我有一个包含部分的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>
Run Code Online (Sandbox Code Playgroud)

现在,基本上这些部分在DOM准备好时加载.有没有办法可以检查特定部分何时完成加载?一旦完成加载,我需要克隆该部分并将其放置在"Placeafterthis"div之后.有关如何实现这一目标的任何建议?

Ori*_*ori 6

您可以使用a MutationObserver来检测何时添加节点.k-content,使用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
Run Code Online (Sandbox Code Playgroud)