D3选择元素的函数有两个:select和selectAll
这里的选择器指的是CSS选择器。
select和select All函数中传递的参数有两种:
另:如果要选择body中的所有p元素,除了使用CSS的派生选择器作为参数之外,还可以采用“连缀语法”。
d3.select("body").selectAll("p");
select和selectAll函数返回的对象称为选择集(selection),添加、删除、设定网页中的元素,都得使用选择集。
2.1 查看状态
查看选择器的函数共有三种:
<body>
<p>段落1</p>
<p>段落2</p>
<p>段落3</p>
<script>
var p = d3.selectAll("p");
console.log(p.empty());//false
console.log(p.node());//<p>段落1</p>
console.log(p.size());//3
</script>
</body>
2.2 设定和获取属性
设定和获取选择集属性的函数共6个:
d3.select("p").attr("id","para");
//四种写法
.classed("red",true);
.classed({"red":true,"blue":true});
.classed("red",true);
.classed("red blue",true);
//省略第二个参数
.classed("red");//返回true或false
selection.style(name[,value[,priority])
设定或获取选择集的样式,name是样式名,value是样式值。如果只保留第一个参数,则返回该样式的值。
d3.select("p")
.style("color","red")
.style("font-size","30px");
//或者以下写法
d3.select("p")
.style({"color":"red","font-size":"30px"})
元素标签将添加如下属性:
<p style="color: red;font-size:30px;"></p>
selection.property(name[,value])
设定或获取选择集的属性,name是属性名,value是属性值。如果省略value,则返回匹配的第一个非空元素的属性值。
有部分属性不能用attr()来设定和获取,例如input的value属性,在input中输入字符test,标签中并不会添加value="test",这种情况就要使用property()。
d3.select("#fname").property("value");
d3.select("#fname").property("value","ZhangSan");
<p>This <span>is</span> a 段落</p>
console.log(d3.select("p").text());//This is a 段落
<p>This <span>is</span> a 段落</p>
console.log(d3.select("p").html());//This <span>is</span> a 段落
我们可以为选择集添加、插入和删除元素。
<body>
<p>Car</p>
<p id="plane">Plane</p>
<p>Ship</p>
<script>
var body = d3.select("body");//选择body元素
//在body元素中所有元素的末尾处添加一个p元素,内容为Train
body.append("p").text("Train");
//在body中id为plane的元素前添加一个p元素,内容为Bike
body.insert("p","plane").text("Bike");
//选择id为plane的元素
var plane = d3.select("#plane");
//删除id为plane的元素
plane.remove();
</script>
</body>
原文:https://www.cnblogs.com/superjishere/p/12108000.html