我的问题是关于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>
谢谢。
答案 0 :(得分:0)
我认为您可以使用1
来获取之前删除的元素的索引。然后只需添加var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.removedNodes) {
var elem = mutation.removedNodes;
var prevElement = $(mutation.previousSibling.previousElementSibling);
var removedIndex = prevElement.index() + 1;
console.dir(removedIndex);
}
});
});
即可获取已删除的元素索引:
+