javascript - 在部分元素完成加载后捕获事件

标签 javascript jquery html 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>

现在基本上这些部分是在 DOM 准备就绪时加载的。有什么方法可以检查特定部分何时完成加载?完成加载后,我需要克隆该部分并将其放置在“Placeafterthis”div 之后。关于如何实现这一点有什么建议吗?

最佳答案

您可以使用 MutationObserver检测何时将节点添加到 .k-contentclone它们使用 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/

相关文章:

html - 如何摆脱 <a hrefs> 和 <img> 之间的空白

javascript - Chrome Devtools 中 JavaScript 字符串中存在未知字符

javascript - 表单提交不能正确使用 jquery

javascript - 如何使用 Javascript 对 Angular 移动元素?

jquery - 每次 PJAX 表单更新时重复查询字符串参数 - 414 Request-URI Too Large

javascript - 如何在 HTML 元素之后放置文本光标?

Javascript:从对象数组中提取对象,并将它们放入新数组中

jquery - 如何使用 jQuery 从表中选择 tr 的范围

javascript - jQuery 单击事件样式表更改不起作用

html - 如何在图像上显示可见的 Div