我有以下代码来遍历所有矩形节点:
d3.selectAll("svg g rect")
.on('mouseover', function (d) {
console.log(this);
});
控制台.log打印:
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="805.625" y="0" width="13.75" height="229.018" >...</rect>
如何访问 rect 标签的名称属性(具有值"UK"
(?我试过this.name
但它不起作用。
> 获取name
值的惯用 D3 方法是使用selection.attr()
作为getter:
d3.select(this).attr("name")
这是演示:
d3.select("rect")
.on('mouseover', function(d) {
console.log(d3.select(this).attr("name"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>
在内部,selection.attr()
使用getAttribute
(或getAttributeNS
(。因此,它等效于:
this.getAttribute("name")
这是演示:
d3.select("rect")
.on('mouseover', function(d) {
console.log(this.getAttribute("name"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect class="cls" name="UK" style="fill: #fdb462;" transform="translate(52 50)" x="0" y="0" width="200" height="100"></rect>
</svg>