0

D3.js を使用してデータをマップするプログラムで、Opentip.js の機能セットを利用しようとしています。

新しい Opentip オブジェクトを、マップを構成する名前のない要素に関連付ける方法がわかりません。

これは、私が取っているアプローチを示すコードの抜粋です。

<script type="text/javascript">
var dataset = [[4,2,'Bob'], [5,7,'Sally'], [2,2,'Marvin']];
var width = 38;
var height = 38;
var margin = 20;

function giveX(d) { return d[0] * width + margin }
function giveY(d) { return d[1] * height + margin }

var mapdiv = d3.select("#map")
    .append("svg")
    .attr("height", 680)
    .attr("width", 980)
    .style('border', '1px solid black')

var pips = mapdiv.selectAll("circle")
    .data(dataset)
    .enter().append("circle")
        .style("fill", "red")
        .style("stroke", "black")
        .attr("cx", function(d) {return giveX(d)})
        .attr("cy", function(d) {return giveY(d)})
        .attr("r", width/2)
</script>   

Opentip オブジェクトのコンストラクターは要素識別子を指定するだけでよいのですが、動的に作成された「円」要素を参照する方法がよくわかりません。

selectAll() 呼び出しにコードを追加しようとしましたが、うまくいきません。

4

1 に答える 1

2

data-ot属性を使用した簡単な例を次に示します。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/downloads/opentip-native.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/css/opentip.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <script>
      
      var svg = d3.select('body')
        .append('svg')
        .attr('width', 200)
        .attr('height', 200);
        
      svg.selectAll('circle')
        .data(d3.range(10))
        .enter()
        .append('circle')
        .attr('cx', function(d) { return Math.random() * 200 } )
        .attr('cy', function(d) { return Math.random() * 200 } )
        .attr('r', 10)
        .style('fill', 'steelblue')
        .attr("data-ot", function(d,i){
          return "Circle " + i;
        });
      
    </script>
  </body>

</html>

そして、コンストラクターを使用した例を次に示します。

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/downloads/opentip-native.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/opentip/2.4.6/css/opentip.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <script>
      
      var svg = d3.select('body')
        .append('svg')
        .attr('width', 200)
        .attr('height', 200);
        
      svg.selectAll('circle')
        .data(d3.range(10))
        .enter()
        .append('circle')
        .attr('cx', function(d) { return Math.random() * 200 } )
        .attr('cy', function(d) { return Math.random() * 200 } )
        .attr('r', 10)
        .style('fill', 'steelblue')
        .each(function(d,i){
          new Opentip(this).setContent("Circle " + i);
        })
      
    </script>
  </body>

</html>

于 2016-07-31T23:38:20.093 に答える