我是d3js的新手,我正试图从SVG元素中获取文本值。下面是我的代码html和javascript:
HTML在d3.json加载之前:
<div id="model_container" style="position: fixed; top: 0px; bottom: 0px; left: 0px; right: 20%">
</div>
<span>
<button onclick="getAllMapReactions();">ADD</button>
</span>
HTML d3.json加载后:
<div id="model_container" style="position: fixed; top: 0px; bottom: 0px; left: 0px; right: 20%">
.
.
.
.
<g id='reactions'>
<g id='r0' class='reaction'>
<g class='reaction-label-group' transform='translate(360,500)'>
<text class='reaction-label label'>HELLO</text>
<g id='r1' class='reaction'>
<g class='reaction-label-group' transform='translate(365,500)'>
<text class='reaction-label label'>HELLO2</text>
</div>
<span>
<button onclick="getAllMapReactions();">ADD</button>
</span>
JavaScript的:
d3.json(document.getElementById("model").value, function(error, data) {
if (error) console.warn(error);
var options = {menu: 'all', canvas_size_and_loc: { x: '200', y: '200', width: '5000', height: '5000' }};
var b = escher.Builder(null, data, null, d3.select('#model_container'), options);
b.map.new_reaction_from_scratch('GAPD',{ x: 350, y: 315 }, 90);
b.map.new_reaction_from_scratch('PGK',{ x: 950, y: 315 }, 90);
b.map.select_all();
});
function getAllMapReactions() {
var reactionsVar = [];
reactionsVar = d3.selectAll(".reaction-label-group").each(function (d) { reactionsVar.push(d3.select(this).text())});
console.log(reactionsVar);
alert(reactionsVar);
}
从上面,我想从<text class='reaction-label label'>HELLO</text>
中提取“HELLO”或“HELLO2”,但是我得到了一个svg对象。
答案 0 :(得分:2)
您选择的是<g>
元素,而不是<text>
。请注意选择器:
function getAllMapReactions() {
var reactionsVar = [];
d3.selectAll(".reaction-label-group text").each(function (d) {
reactionsVar.push(d3.select(this).text())
});
console.log(reactionsVar);
}