【D3.js 学习总结】3、D3选择器

    xiaoxiao2026-02-20  15

    用过kissy的都知道它的选择器有 Node.one 和 Node.all 两个,前一个是选择第一个结果,后一个是选择所有结果;D3的选择器跟kissy类似,只是名字换成了 d3.select 和 d3.selectAll ,应该比较好理解;

    例如:

    选中body标签

    var body = d3.select('body');

    选中所有p标签

    var p = d3.selectAll('p');

    不一样的地方在于转换为原生dom时,Kissy是 Node.all('body')[0] 而D3是 d3.selectAll('body')[0][0]

    D3选择器还有以下这些方法帮助我们对节点或数据做一些操作

    方法名含义示例selection.append创建并追加一个新元素p.append('span')selection.attr取得或设置属性的值p.attr('class','demo')selection.call为当前选择调用一个函数p.call(function(d){d.text('demo')})selection.classed添加或移除CSS类p.classed('demo',true)selection.data为一组元素分别取得或设置数据p.data([1,2,3],function(d){return d;})selection.datum为单个元素取得或设置数据p.datum(1)selection.each为每个选中的元素调用一个函数p.data([1,2,3]).each(function(d,i){console.log(d)})selection.empty如果选择是空则返回trueconsole.log(p.empty())selection.enter为缺失的元素返回占位符p.enter()selection.exit返回不再需要的元素p.exit()selection.filter基于数据过滤选择p.data([1,2,3]).filter(function(d,i){return d%2 == 0})selection.html取得或设置innerHTML内容p.html('12')selection.insert在已存在元素之前创建并插入一个元素p.insert('span')selection.interrupt如果有过渡的话,立即中断当前的过渡p.interrupt()selection.node返回选择中的第一个节点p.node().innerHTML = 'demo'selection.on为交互添加或移除事件监听器p.on('click',function(d){console.log(d)})selection.order重排列文档中的元素,以匹配选择var div = d3.select("body").selectAll("div") .data(["a", "b", "f"]); div.enter().append("div") .text(String); var div = d3.select("body").selectAll("div") .data(["a", "b", "c", "d", "e", "f"], String); div.enter().append("div") .text(String); div.order();selection.property取得或设置行内属性d3.select('input').property('checked')selection.remove从当前文档中移除当前元素p.remove()selection.select为每个选中元素的在选择一个后代元素p.select('span')selection.selectAll为每个选中元素的在选择多个后代元素p.selectAll('span)selection.size返回选择中的元素数p.size()selection.sort基于数据排列文档中的元素p.data([1,3,2]).sort(function (a,b) {return a>b;})selection.style取得或设置样式属性p.style('width','100px')selection.text取得或设置文本内容p.text('demo')selection.transition在选中元素上开启过渡p.transition()
    最新回复(0)