如何访问“先前的兄弟姐妹"?遍历选择时的"this"的概念? [英] How to access "previous sibling" of `this` when iterating over a selection?

查看:61
本文介绍了如何访问“先前的兄弟姐妹"?遍历选择时的"this"的概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,假设$sel是任意 d3.js选择项:

In the following code, assume that $sel is some arbitrary d3.js selection:

$sel.each(function(d, i, j) {
              var prev = ??? ;
              ...
          });

我可以替换???来为prev分配一个由以前的this 兄弟姐妹组成的d3.js选择(如果存在)吗?

What can I replace the ??? to assign to prev a d3.js selection consisting of the previous sibling of this (if any such exists)?

(如果this是第一个孩子,因此没有先前的同级,则应为prev分配一个空的d3.js选择.)

(If this is a first child, and therefore has no previous sibling, an empty d3.js selection should be assigned to prev.)

推荐答案

可能很简单

var prev = d3.select(this.previousSibling);

如果您仅对元素节点感兴趣,则可以参加

If you are interested in element nodes only you would go for

var prev = d3.select(this.previousElementSibling);

d3.selectAll(".c").each(function() {
    console.log(d3.select(this));                         // Element <p class="c"></p>
    console.log(d3.select(this.previousSibling));         // text node containing whitespace between b and c
    console.log(d3.select(this.previousElementSibling));  // Element <p class="b"></p>
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div>
    <p class="a"></p>
    <p class="b"></p>
    <p class="c"></p>
    <p class="d"></p>
    <p class="e"></p>
</div>

这篇关于如何访问“先前的兄弟姐妹"?遍历选择时的"this"的概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆