我正在学习 D3,并且在使用选择运算符时遇到了问题。
具体来说,为什么下面的代码要添加<p>
元素在身体之外,而不是在身体内部?
var pData1 = d3.select("body").select("p").data([1]).enter().append("p");
我正在使用一个完全空白的 HTML 文件<head>
and <body>
标签进行测试。
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script type="text/javascript" src="d3.min.js"></script>
</head>
<body>
</body>
</html>
(这重复了 Lars Kotthoff 的回答中的内容,但我花了时间创建演示,所以我想我仍然会发布。)
问题是select
,不像selectAll
,不会为添加到的元素重新定义父元素enter()
选择。
d3.select("body").select("p#a")
.data([1])
.enter().append("p").attr("id", "a")
.text("This paragraph is appended to <html> (the document root)
because no selectAll statement reset the parent element.");
d3.selectAll("p#b")
.data([1])
.enter().append("p").attr("id", "b")
.text("This paragraph is appended to <html>
because the selectAll statement is called directly on the root.");
d3.selectAll("body").select("p#c")
.data([1])
.enter().append("p").attr("id", "c")
.text("This paragraph is also appended to <html>
because the last selectAll statement was called directly from the root.");
d3.select("body").selectAll("p#d")
.data([1])
.enter().append("p").attr("id", "d")
.text("This paragraph is appended to <body>
because the selectAll statement is a sub-selection of the body selection.");
d3.selectAll("body").selectAll("p#e")
.data([1])
.enter().append("p").attr("id", "e")
.text("This paragraph is also appended to <body>
because the final selectAll statement is a sub-selection of the body.");
http://fiddle.jshell.net/eLF4H/
在 a 后使用 Enter 链是不常见的select
语句(相对于 selectAll),因为如果要进行数据连接,通常您会选择多个元素。然而,如果您想创建元素(如果不存在)或更新它(如果存在),您有两个选择:
-
使用 selectAll 语句后跟数据连接
var pdata1 = d3.select("body").selectAll("p#data")
//select element if it exists
.data([dataObject]);
//join to the current data
pdata1.enter().append("p").attr("id", "data");
//create element if required
pdata1.text(function(d){return d.textValue;});
//set or update the element based on the data
-
如果需要,使用 if 语句创建元素并使用.datum()绑定数据
var pdata1 = d3.select("p#data")
//select element if it exists
if ( pdata1.empty() ) {
pdata1 = d3.select("body").append("p").attr("id", "data");
//create element if required
}
pdata1.datum(dataObject)
//note that you don't need to put the data into an array
.text(function(d){return d.textValue;});
//set or update the element based on the data
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)