Javascript活动MutationObserver可处理各种元素

时间:2018-06-25 15:34:14

标签: javascript mutation-observers queryselectall

required中的li号更改时,我想添加或删除ul attr。 如果没有li,则将添加required属性;如果没有li,则将删除required属性。

该功能很好用,但仅适用于前input[type="file"]个 我希望函数为页面中的所有文件输入提供帮助。 我希望它能观察到每一个方面的变化。

我以为是

const fileList = document.querySelectorAll('ul.file-list')[x];
observer.observe(fileList, {
    childList: true
})

但是我有两个问题:

  1. 如何找到工作的ul.file-list(而不是x)的阵列位置。
  2. 我不想使用事件监听器。

任何帮助都会很棒。

const observer = new MutationObserver(function(mutations){
    mutations.forEach(function(mutation){
        let liLength = mutation.target.getElementsByTagName("li").length;
        if(mutation.addedNodes.length){
            console.log('added',mutation);
            if(liLength != 0){
                mutation.target.parentElement.getElementsByTagName('input')[0].required = false;
            }
        }
        if(mutation.removedNodes.length){
            if(liLength == 0){
                mutation.target.parentElement.getElementsByTagName('input')[0].required = true;
            }
        }
    });
});

const fileList = document.querySelector('ul.file-list');
observer.observe(fileList, {
    childList: true
})

这是html标记。这是我页面中27个'ul'之一

<div class="custom-file" id="tz-file">
    <label class="custom-file-label" for="tzfile">add file</label>
    <ul class="file-list">
        <li><a href="./uploads/9999999/1.pdf" target="_blank"> 1.pdf </a>
            <span class="item-file" id="2018-9999999-21314-1">remove file</span></li>
    </ul>
    <input type="file" class="custom-file-input" id="tzfile" name="tzfile">
</div>

0 个答案:

没有答案