如何用一个值函数设置多个属性? [英] How to set multiple attributes with one value function?

查看:32
本文介绍了如何用一个值函数设置多个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定包含多个数据元素的数据,例如对象或数组,是否可以使用单个值函数在选择上设置多个属性?

Given a datum containing multiple data elements, such as an object or array, is it possible to set multiple attributes on a selection with a single value function?

例如类似:

var data = [{ 'x': 10, 'y': 20, 'r': 5 }];
d3.select('body').append('svg').selectAll('circle')
    .data(data)
    .enter().append('circle')
    .attr('cx cy r', function (d) {
        return [d.x, d.y, d.r];
    });

代替:

var data = [{ 'x': 10, 'y': 20, 'r': 5 }];
d3.select('body').append('svg').selectAll('circle')
    .data(data)
    .enter().append('circle')
    .attr('cx', function (d) {
        return d.x;
    });
    .attr('cy', function (d) {
        return d.y;
    });
    .attr('r', function (d) {
        return d.r;
    });

推荐答案

UPDATE(2016 年 7 月 8 日)此答案适用于 d3 v3.x — 不适用于 v4.x.对于后一个版本,请参见同样位于此页面上的 Tim Hayes 的回答.或者...只需在我下面的答案中将 attrattrs 交换,并且不要忘记 require/import/script-embed d3-selection-multi.还有...不要错过使用 .each 的部分,它可能对您有用.

UPDATE (July 8th 2016) This answer applies to d3 v3.x — NOT v4.x. For the latter version, see Tim Hayes's answer, also on this page. Or... just swap attr with attrs in my answer below, and don't forget to require/import/script-embed d3-selection-multi. And... don't miss the bit about using .each, which may be useful to you.

是的,可以通过传入散列(如 jQuery 的 css() 方法):

Yeah, it's possible by passing in a hash (like jQuery's css() method):

d3.select('body').append('svg').selectAll('circle')
  .data(data)
.enter().append('circle')
  .attr({
    cx: function (d) { return d.x; },
    cy: function (d) { return d.y; },
    r:  function (d) { return d.r; }
  });

这也适用于 style().

如果重复出现的 function (d) {} 开始感觉太多了,这是另一种方法:

If the reoccurring function (d) {} start to feel like too much, this is another approach:

d3.select('body').append('svg').selectAll('circle')
  .data(data)
  .enter().append('circle')
  .each(function (d) {
    d3.select(this).attr({
      cx: d.x,
      cy: d.y,
      r:  d.r
    });
  })

注意:此功能仅存在于 d3.js v2.10.0 或更高版本

NOTE: this feature only exists in d3.js v2.10.0 or higher

这篇关于如何用一个值函数设置多个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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