获取元素变异发生的索引位置

4

我的问题和DOM变异有关。 多年前,Web开发人员能够处理对DOM所做的更改(称为DOM变异)。

我使用了这个函数来检查元素是否已从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>

谢谢你。

感谢您。

1个回答

1

我认为您可以使用mutation.previousElement来获取被删除元素之前的元素索引。然后只需添加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);
    }
  });
});

哇,太棒了。你节省了我的时间。我非常需要索引号来拼接一个包含已移除元素数据的数组。再次感谢你。 - james Oduro
我认为创建mutationOberser() API的谷歌团队应该添加一个索引属性的mutationRecord。这将使事情变得简单。 - james Oduro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接