我正在尝试在SVG中获取一个文本元素,以便通过选项更改进行更新。搜索之后,我已经能够到达我可以看到的位置(在控制台中)页面初始加载中的选项更改,以及选项更改时,但是我没有成功获取要更改的数字。任何帮助,将不胜感激。
<!DOCTYPE html>
<html>
<head>
<title>Dropdown Test</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<select id="filter">
<option value="GroupOne">Group One</option>
<option value="secondTen">Group Two</option>
<option value="thirdTen">Group Three</option>
</select>
<section id='svgCanvas'>
</section>
<script>
var width = 100;
var height = 100;
var numberData = [
{"Number":10,"Group":"GroupOne"},
{"Number":13,"Group":"GroupTwo"},
{"Number":6,"Group":"GroupThree"},
];
var canvas = d3.select("#svgCanvas")
.append('svg')
.attr('height',height)
.attr('width',width);
function filterData(filterCriteria) {
console.log(filterCriteria);
var svgNumber = canvas.selectAll('text')
.data(numberData);
svgNumber.enter()
.append('text')
.filter(function(d){return d.Group == filterCriteria;})
.text(function(d){return d.Number;})
.attr('x',10)
.attr('y',30)
.attr('fill','#000000')
.attr('id','numberText');
svgNumber.exit().remove();
};
filterData('GroupOne');
d3.select("#filter")
.on('change', function() {
var filter = d3.select(this).property('value');
filterData(filter);
console.log(filter);
});
</script>
</body>
</html>
答案 0 :(得分:1)
您需要进行一些更改:
merge
选项(从第二次开始,您的“输入”选择始终为空)。以下是工作代码:
var width = 100;
var height = 100;
var numberData = [{
"Number": 10,
"Group": "GroupOne"
}, {
"Number": 13,
"Group": "GroupTwo"
}, {
"Number": 6,
"Group": "GroupThree"
}, ];
var canvas = d3.select("#svgCanvas")
.append('svg')
.attr('height', height)
.attr('width', width);
function filterData(filterCriteria) {
var svgNumber = canvas.selectAll('text')
.data(numberData.filter(function(d) {
return d.Group == filterCriteria;
}));
svgNumber.exit().remove();
svgNumber.enter()
.append('text')
.attr('x', 10)
.attr('y', 30)
.attr('fill', '#000000')
.attr('id', 'numberText')
.merge(svgNumber)
.text(function(d) {
return d.Number;
});
};
filterData('GroupOne');
d3.select("#filter")
.on('change', function() {
var filter = d3.select(this).property('value');
//or just--> var filter = this.value;
filterData(filter);
});
<script src="https://d3js.org/d3.v4.min.js"></script>
<select id="filter">
<option value="GroupOne">Group One</option>
<option value="GroupTwo">Group Two</option>
<option value="GroupThree">Group Three</option>
</select>
<section id='svgCanvas'>
</section>