我有一个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:无法转换表达式以返回指定的类型。
如何将DOMSubtreeModified
事件转换为MutationObserver
?
答案 0 :(得分:6)
sel
变量作为观察目标; 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});