【问题标题】:Get Index position of element mutation happened on获取元素突变的索引位置发生在
【发布时间】: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


    【解决方案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);
        }
      });
    });
    

    【讨论】:

    • 哇。那行得通。你节省了我的时间。我非常需要索引号来拼接一个包含已删除元素数据的数组。再次感谢您
    • 我认为创建mutationOberser() API 的google guyz 应该添加一个索引属性的mutationRecord。这会让事情变得简单。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    相关资源
    最近更新 更多