Javascript D3.js 前置(类似于 jQuery 前置)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26234636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
D3.js prepend (similar to jQuery prepend)
提问by Mia
I like the usage of append in D3, and I'm looking for prepend.
我喜欢 D3 中 append 的用法,我正在寻找 prepend。
Does this exist in D3?
这在D3中存在吗?
回答by Gilsha
You can use
您可以使用
selection.insert(newElement[, anotherExistingElement])
For example:
例如:
selection.insert("div",":first-child")
The above code will insert a divbefore the first child of selected element. Check documentationto learn more.
上面的代码将div在所选元素的第一个子元素之前插入一个。查看文档以了解更多信息。
Another possible way of inserting elements before any node (including plain texts):
在任何节点(包括纯文本)之前插入元素的另一种可能方式:
var parentEl = d3.select("div").node();
parentEl.insertBefore(document.createElement("div"), parentEl.childNodes[0]);
<script src="https://d3js.org/d3.v3.min.js"></script>
<div>
This is a plain text
<a></a>
</div>
回答by Andrew Reid
Selection.lower()
选择.lower()
selection.lower()will place an element as the first child of its parent.
selection.lower()将一个元素作为其父元素的第一个子元素。
Together with d3's append, selection.append().lower()can replicate jQuery's prepend
与 d3 的append一起,selection.append().lower()可以复制 jQuery 的prepend
Since D3 v4+, D3 has both selection.raise()and selection.lower()methods. These are used most frequently to move elements in an SVG so that certain elements appear overtop of others, where ordering of SVG elements in the DOM determines draw order. But, they can be used for any element in the DOM.
从 D3 v4+ 开始,D3 既有selection.raise()和selection.lower()方法。这些最常用于移动 SVG 中的元素,以便某些元素出现在其他元素之上,其中 DOM 中 SVG 元素的顺序决定了绘制顺序。但是,它们可以用于 DOM 中的任何元素。
Here's a quick demonstration using divs and paragraphs:
这是使用 div 和段落的快速演示:
var div = d3.select("div");
div
.append("p")
.text("Inserted")
.lower();
console.log(div.html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="div">
Text
<p> Child Paragraph </p>
</div>
The snippet takes a div with the following contents:
该代码段采用具有以下内容的 div:
Text
<p> Child Paragraph </p>
And uses d3 to append a new paragraph and then lower it so that the structure is as follows:
并使用d3追加一个新的段落,然后将其降低,结构如下:
<p>Inserted</p>
Text
<p> Child Paragraph </p>
And for comparison with with jQuery's prepend:
并与 jQuery 的 prepend 进行比较:
var div = $("div");
div
.prepend("<p>Inserted</p>");
console.log(div.html());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div">
Text
<p> Child Paragraph </p>
</div>
More Info
更多信息
The selection.lower() is implemented as such (see docsfor more info):
selection.lower() 是这样实现的(有关更多信息,请参阅文档):
selection.each(function() {
this.parentNode.insertBefore(this, this.parentNode.firstChild);
});

