实现 MutationObserver 代替 DOMSubtreeModified

2024-03-27

我有一个select[multiple]我已经上过课custom-multiselect在我正在捕捉的页面上DOMSubtreeModified事件如下:

HTML:

<select class="custom-multiselect"></select>

JQuery:

$('.custom-multiselect').each(function (i, select) {
    var sel = this;
    adjustHeight(sel); //Custom function
    //Binding DOMSubtreeModified to catch if the select list gets modified by the user
    $(sel).on('DOMSubtreeModified', function () {            
        adjustHeight(sel);
    });
    //For Internet Explorer
    $(sel).on('propertychange', function () {
        adjustHeight(sel);
    });
});

这种方法效果完美。我想转换DOMSubtreeModified函数进入MutationObserver since DOMSubtreeModified已折旧。

所以我做了这样的事情:

var observer = new MutationObserver(function (mutation) {
    mutation.forEach(function (m) {
        if (m.type == 'subtree') {
            adjustHeight(this);//Can I use m.target here?
        }
    });
});
observer.observe(document.querySelector('select.custom-multiselect'), {
    subtree: true
});

但我最终得到了错误

类型错误:无法将表达式转换为返回指定的类型。

我怎样才能转换我的DOMSubtreeModified需观察的事件MutationObserver?


  • 将代码放在旧 DOM 事件的位置并使用您的sel变量作为观察目标;
  • Use childListMutationObserver 中的选项因为subtree没有指定要寻找什么;
  • 由于您只订阅一种类型,因此无需检查突变。
$('.custom-multiselect').each(function() {
    var sel = this;
    adjustHeight(sel);

    new MutationObserver(function() {
        adjustHeight(sel);
    }).observe(sel, {childList: true, subtree: true});
});

或者,如果你喜欢.bind因为某些原因:

new MutationObserver(adjustHeight.bind(null, sel))
    .observe(sel, {childList: true, subtree: true});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

实现 MutationObserver 代替 DOMSubtreeModified 的相关文章