唯一ID,D3中生成的矩形的ID名称 [英] unique id , id name for generated rectangles in D3
本文介绍了唯一ID,D3中生成的矩形的ID名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码使用D3生成11个正方形:
The following code generates 11 squares using D3:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.js"></script>
<script type="text/javascript">
var width = 1000,
height = 250,
margin = 4,
nRect = 11,
rectWidth = (width - (nRect - 1) * margin) / nRect,
svg = d3.select('#chart').append('svg')
.attr('width', width)
.attr('height', height);
var data = d3.range(nRect),
posScale = d3.scaleLinear()
.domain(d3.extent(data))
.range([0, width - rectWidth]);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', posScale)
.attr('width', rectWidth)
.attr('height', height);
</script>
我的计划是以后使用这些正方形作为链接,无论如何,我可以在生成的每个正方形上放置唯一的ID或名称吗?
My plan is to use those squares later as links, is there anyway I can put a unique ID or name on every square generated?
推荐答案
最简单的解决方案是使用矩形的索引:
The simplest solution is using the rectangles' indices:
.attr("id", function(d,i){ return "rect" + i})
请记住,ID不能以数字开头.这就是为什么我将字符串rect
与每个矩形的索引连接在一起的原因.
Have in mind that IDs cannot start by number. That's why I'm concatenating the string rect
with each rectangle's index.
这是一个演示:
var width = 1000,
height = 250,
margin = 4,
nRect = 11,
rectWidth = (width - (nRect - 1) * margin) / nRect,
svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
var data = d3.range(nRect),
posScale = d3.scaleLinear()
.domain(d3.extent(data))
.range([0, width - rectWidth]);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr("id", function(d,i){ return "rect" + i})
.attr('x', posScale)
.attr('width', rectWidth)
.attr('height', height);
<script src="https://d3js.org/d3.v4.min.js"></script>
这篇关于唯一ID,D3中生成的矩形的ID名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文