【问题标题】:Equivalent document.querySelector inside Mutation Observer dynamic elementsMutation Observer 动态元素中的等效 document.querySelector
【发布时间】:2016-07-25 11:19:00
【问题描述】:

我正在使用Mutation Observer 来收听新添加的元素,它对所有元素都可以正常工作,但对于Switchery jQuery 插件却没有,因为 Switchery 通过 [document.querySelector] 获取元素

这是我的代码...

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
});

感谢您的帮助。

【问题讨论】:

    标签: jquery-selectors mutation-observers switchery


    【解决方案1】:

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

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

    下面是一个通过 jQuery 查找元素并将 Switchery 应用于每个元素的示例。所以,在你的代码中 sw_current = $(this).find('.switchery-element'); 之后做类似的事情。

    	$(function() {
            sw_current = $(this).find('.switchery-element');
            sw_current.each(function() {
    	        var switchery = new Switchery(this);
            })
    
        });
    @import url("http://abpetkov.github.io/switchery/dist/switchery.min.css");
    <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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-27
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 2017-05-10
      相关资源
      最近更新 更多