【发布时间】:2017-09-26 08:50:33
【问题描述】:
我的问题是关于 DOM 突变。 多年前,Web 开发人员能够处理对 DOM 所做的更改(称为 DOM Mutations)。
我使用这个函数来检查一个元素是否已从 DOM 中删除。 我还能够在元素从 DOM 中删除之前获取元素的索引位置 index():
function NodeRemovedEventTrigger() {
jQuery( "body" ).bind(
"DOMNodeRemoved",
function( objEvent ){
// Append event to log display.
var elem = $(objEvent.target);
if(elem.hasClass('feed-container')) {
var i = elem.index();
console.log(i);//get index position of the element
}
}
);
}
由于 DOMNodeRemoved 在某些浏览器中已被弃用且不支持,如何使用 MutationObserver() 方法实现与上述功能类似的功能。我的重点是获得索引位置
我尝试过的似乎对我不起作用:
// select the target node
var target =document.getElementById('post-line');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.removedNodes) {
//if the element removed has class='post-container' , then get the index position
var elem = mutation.removedNodes;
console.log(elem.index());//get index position
}
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true,removedNodes:NodeList[0]};
// pass in the target node, as well as the observer options
observer.observe(target, config);
HTML:
<div id="post-line">
<div class="post-container">
<div><span></span></div>
</div>
<div class="post-container">
<div><span></span></div>
</div>
<div class="post-container">
<div><span></span></div>
</div>
</div>
谢谢。
【问题讨论】:
标签: javascript mutation