【问题标题】:What is the cleanest way to get nextElementSibling (previousElementSibling) from MutationRecord?从 MutationRecord 获取 nextElementSibling (previousElementSibling) 的最干净的方法是什么?
【发布时间】:2014-01-29 02:24:10
【问题描述】:

我想知道对于给定的MutationRecord,在Elements 周围找到最干净的方法是什么?

MutationRecord.nextSibling.previousSibling 属性,但可能包含文本节点,我需要获取常规元素节点。

工作示例在这里:http://jsfiddle.net/tomalec/ceku2/

我尝试过使用

mutation.addedNodes[0].previousElementSibling;
mutation.addedNodes[mutation.addedNodes.length - 1].nextElementSibling);

http://jsfiddle.net/tomalec/Q2HFY/2/

不过看起来有点冒险,而且对于被移除的完全不起作用。

mutation.removedNodes[0].previousElementSibling; //null
mutation.removedNodes[mutation.removedNodes.length - 1].nextElementSibling); //null

http://jsfiddle.net/tomalec/Q2HFY/3/

【问题讨论】:

    标签: javascript dom mutation-observers


    【解决方案1】:

    这绝对是有风险的。由于 MutationRecords 是批量处理的,因此 DOM 的当前状态可能难以确定突变的周围节点。例如,如果您有两个 MutationRecord 发送到 MutationObserver,第二个 MutationRecord 可能已经删除了第一个的周围节点,这意味着您无法通过 simple DOM 检查来完成。

    为了使问题具体化,请使用以下 html:

    <ul><li>One</li><li>Two</li><li>Three</li></ul>
    

    还有这个javascript:

    var ul = document.querySelector('ul');
    while (ul.lastChild) ul.removeChild(ul.lastChild);
    

    变异观察者会得到两个变异记录,你必须做一些花哨的工作才能确定它们是相互关联的。我不确定该算法会是什么样子,或者是否在所有情况下都可行。

    无论如何,这是我的示例 jsfiddle:

    http://jsfiddle.net/theazureshadow/88egh/

    如果您可以限制 MutationObserver 必须处理的情况,也许您可​​以做一些更简单或更聪明的事情。

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 2019-12-19
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-10-03
      相关资源
      最近更新 更多