如何在d3.js中将图例文本设为可点击

时间:2016-08-26 12:15:56

标签: javascript jquery d3.js



var text=["level1","level2","level3"]
var color=['blue','black','green']

var legend = svg.append("g")
  .attr("class", "legend")
  .attr("id","ad")
  .attr('transform', 'translate(210,40)');
  
legend.selectAll('#ad')
  .data(text)
  .enter()
  .append("rect")
  .attr("x", function(d, i){ return i *  100;})
  .attr("y", height)
  .attr("width", 10)
  .attr("height", 10)
  .style("fill",function(d,i){return color(i);});

legend.selectAll('text')
  .data(text)
  .enter()
  .append("text")
  .attr("x", function(d, i){ return i *  100 + 15;})
  .attr("y",height+10)
  .attr("class","leg_txt_font")
  .text(function(d,i){ return text[i];});




我已尝试上面的代码来设置图例。如何在d3.js中将图例文本设为可点击 我必须将图例文本设置为可点击..如果我单击图例文本意味着只需要显示警报消息

1 个答案:

答案 0 :(得分:1)

您只需使用on("click", function(){ ... })

selection.on("click", function(d){
    alert(d)
});

在下面的代码段中,点击图例以获取提醒:

var text=["level1","level2","level3"];
var color=['blue','black','green'];

var svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 400);

var legend = svg.append("g")
  .attr("class", "legend")
  .attr("id","ad")
  .attr('transform', 'translate(40,40)');
  
var rects = legend.selectAll('#ad')
  .data(text)
  .enter()
  .append("rect")
  .attr("x", function(d, i){ return i *  100;})
  .attr("y", 50)
  .attr("width", 10)
  .attr("height", 10)
  .style("fill",function(d,i){return color[i];});

var texts = legend.selectAll('text')
  .data(text)
  .enter()
  .append("text")
  .attr("x", function(d, i){ return i *  100 + 15;})
  .attr("y",60)
  .attr("class","leg_txt_font")
  .text(function(d,i){ return text[i];})

texts.on("click", function(d){
  alert(d)
});
text {
  cursor: pointer;
  }
<script src="https://d3js.org/d3.v4.min.js"></script>