我有一个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
,因为 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
});
但我最终得到了错误
TypeError: The expression cannot be converted to return the specified type.
如何将我的 DOMSubtreeModified
事件转换为由 MutationObserver
观察?
最佳答案
- 将代码放在旧 DOM 事件的位置,并使用您的
sel
变量作为观察目标; - 在 MutationObserver 中使用
childList
选项,因为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});
关于javascript - 实现 MutationObserver 代替 DOMSubtreeModified,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971140/