首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >变异观察器动态元素中的等效document.querySelector

变异观察器动态元素中的等效document.querySelector
EN

Stack Overflow用户
提问于 2016-04-05 21:24:08
回答 1查看 472关注 0票数 2

我使用Mutation Observer来监听新添加的元素,它对所有元素都工作得很好,但对于Switchery jQuery插件就不行了,因为Switchery get element by document.querySelector

这是我的代码。

代码语言:javascript
复制
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

var observerjQueryPlugins = function (repeaterWrapper) {

_.each(repeaterWrapper, function (repeaterItem, index) {

    var jq_nodes = $(repeaterItem.addedNodes);

    jq_nodes.each(function () {

        // Color Picker (Working Good)
        $(this).find('.element-wrapper.element-wpcolor .color-picker').wpColorPicker();

        // Switchery using document.querySelector and i need to know the
        // equivalent way to do it inside this loop .. like that

        // Of course this code is WRONG
        sw_current = $(this).find('.switchery-element');

        var switchery = new Switchery( sw_current, {
                disabled: false,
                size: '',
                color: '#8ce196',
                secondaryColor: '#ddd',
                jackColor: '#fff',
                jackSecondaryColor: '#fff'
        });

    });
});

}

new MutationObserver(observerjQueryPlugins).observe(document.body, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2018-11-15 08:45:11

看起来Switchery不是一个jQuery插件。这就是为什么GitHub中的示例代码使用document.querySelector来获取元素来应用它。

在使用jQuery查找元素时,需要使用Switchery. each来处理jQuery的每个DOM元素。

下面是一个通过jQuery查找元素并将Switchery应用于每个元素的示例。因此,在代码中的sw_current = $(this).find('.switchery-element');之后执行类似的操作。

代码语言:javascript
复制
	$(function() {
        sw_current = $(this).find('.switchery-element');
        sw_current.each(function() {
	        var switchery = new Switchery(this);
        })

    });
代码语言:javascript
复制
@import url("http://abpetkov.github.io/switchery/dist/switchery.min.css");
代码语言:javascript
复制
<input type="checkbox" class="switchery-element" checked />Check 1
<p/>
<input type="checkbox" class="switchery-element" checked />Check 2
<p/>
<input type="checkbox" class="switchery-element" checked />Check 3

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://abpetkov.github.io/switchery/dist/switchery.min.js"></script>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36427673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档