简体   繁体   中英

Update d3 body text

How do I best update a body text element from a SVG tree node mouseover event? When I try the following the text is updated, but the SVG is removed from the display. Here is a the code:

var svg = d3.select('body')
  .append('text').text('The Entry Point and M Code: ')
  .attr('class', 'centralText')
  .attr('x', 10)
  .attr('y', 10)
  .attr('text-anchor', 'middle')

  .append('svg')

here is my event code:

var nodeEnter = node.enter().append('g')
    .attr('class', node_class)
    .attr('transform', function(d) {
      return 'translate(' + source.x0 + ',' + source.y0 + ')'; })
    .style('cursor', function(d) {
      return (d.children || d._children) ? 'pointer' : '';})
    .on('click', click)
    .on("mouseover", function(d) {
         d3.select('body')
            .text('M Code: is this')

There are two separate issues that are coming up. First, your initialization of svg is appending it to a text element, which is a bad idea. Second, to update the text you're replacing the body text and not the text element.

Two changes need to be made. First, change your mouseover function to this:

 d3.select('body').select('text')
            .text('M Code: is this');

This would normally fix it, but the second problem is that the svg is appended to the text element so it will still be erased. To fix this, change your declaration to the following:

d3.select('body')
  .append('text').text('The Entry Point and M Code: ')
  .attr('class', 'centralText')
  .attr('x', 10)
  .attr('y', 10)
  .attr('text-anchor', 'middle');

 var svg = d3.select('body').append('svg');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM