【问题标题】:d3.select by attribute valued3.按属性值选择
【发布时间】:2013-12-23 06:40:06
【问题描述】:

我是 d3 的新手。我有这样的定义:

node = node.enter().append("circle")
            .attr('id', function(d){ return d.id; })
            .attr("class", "node")
            .on('mouseover', mouseover_node)
            .on("click", nodeClick);

现在在函数 nodeClick 中,我想访问具有特殊 ID 的节点(或圆)。我正在寻找可以像这样使用的东西:

for(var i=0;i<maxId;i++) {
    d3.select(the node with id = i).do....

有人知道我该怎么做吗?

【问题讨论】:

  • 试试 d3.select("#" + i)
  • 它给了我这些错误: Uncaught SyntaxError: Failed to execute query: '#56' is not a valid selector.

标签: javascript jquery d3.js


【解决方案1】:

你的问题是ids and names must begin with a letter。因此,修改您的代码以在每个 id 前添加一个字符串,例如

.attr('id', function(d){ return 'name' + d.id; })

然后,您可以使用d3.select( '#name' + i ) 选择给定节点。来自the docs D3 选择:

...您可以按标签(“div”)、类(“.awesome”)、唯一性进行选择 标识符(“#foo”)、属性(“[color=red]”)或包含 (“父子”)。

【讨论】:

  • 知道如何在属性 然后是某个值的情况下执行此操作
  • @mireilleraad 在最低级别,您可以选择所有您感兴趣的元素,运行for 循环并挑选出符合您标准的元素。例如:var all_elements = $('.line'); var line_num_big = []; for (var i = 0; i &lt; all_elements.length; i++) { if (parseInt ($(all_elements[i]).attr('id') &gt; 1000) { line_num_big.push(all_elements[i]); }。请原谅格式,一行写不好玩。
  • 文档移动了。上一个版本的固定链接是Docs @ commit 434aee
  • d3.select("[id='" + i + "']") 看起来很有用,但有没有办法指定多个条件?说 id = 1 和 sid = 2?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2014-12-27
  • 2012-12-24
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多