Javascript 实现MutationObserver代替domsubtree
我有一个Javascript 实现MutationObserver代替domsubtree,javascript,jquery,dom,mutation-observers,Javascript,Jquery,Dom,Mutation Observers,我有一个select[multiple],我在我的页面上给了它一个类custom multiselect,我正在为它捕获domsubtreemedited事件,如下所示: HTML: 这种方法完美无瑕。我想将domsubtreemedited函数转换为MutationObserver,因为domsubtreemedited已折旧 所以我做了这样的事情: var observer = new MutationObserver(function (mutation) { mutation.f
select[multiple]
,我在我的页面上给了它一个类custom multiselect
,我正在为它捕获domsubtreemedited
事件,如下所示:
HTML:
这种方法完美无瑕。我想将domsubtreemedited
函数转换为MutationObserver
,因为domsubtreemedited
已折旧
所以我做了这样的事情:
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:无法将表达式转换为返回指定的类型
如何将我的domsubtreemedited
事件转换为MutationObserver
?- 将代码放在旧DOM事件的位置,并使用
变量作为观察目标李>sel
- 在MutationObserver中使用
选项,因为childList
没有指定要查找的内容李>subtree
- 没有必要检查突变,因为您只订阅一种类型
.bind
:
new MutationObserver(adjustHeight.bind(null, sel))
.observe(sel, {childList: true, subtree: true});
在adjustHeight
中,此
肯定不是您想要的-您是否尝试了m.target?我尝试了,但我收到了上述错误。它不让我知道m.target是否有效:-SOK,read-至少,childList,attributes或characterData必须设置为true。否则,“指定了无效或非法的字符串”错误将被抛出-并且没有变异。type==“subtree”
-我很惊讶您的代码竟然达到您声称的程度-哦,我明白了,该错误是因为您没有将childList
、属性
或characterData
中的至少一个设置为true…谢谢,我发现另一个论坛的.type=='subtree'认为它有效,这就是我尝试的原因。目前,它不使用MutationObserver,而是使用DOMSubtreeModified函数。您需要type==“childList
并将childList:true
添加到中。请观察选项
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
});
$('.custom-multiselect').each(function() {
var sel = this;
adjustHeight(sel);
new MutationObserver(function() {
adjustHeight(sel);
}).observe(sel, {childList: true, subtree: true});
});
new MutationObserver(adjustHeight.bind(null, sel))
.observe(sel, {childList: true, subtree: true});