对D3生成的文本对象的子串执行操作

时间:2013-11-10 10:05:30

标签: d3.js

我想知道在用户正在进行数据可视化的过程中,将叙述性文本段落向网页侧面滚动。作为其中的一部分,将功能添加到该文本的某些子字符串会很好,例如打开与其相关的弹出图像。但我想不出任何方法可以告诉D3对文本元素的子串进行客体化,以便它们可以响应像mouseover这样的运算符。

以下是一个示例,plus jfiddle

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
    <title>Substring click</title>
    <script type="text/javascript" src="scripts/d3.v3.js"></script>
</head>
<body>
<!-- example line -->
<p>The most interesting <A href="https://en.wikipedia.org/wiki/The_Most_Interesting_Man_in_the_World">man</A> in the world</p>
<div/>

<script type="text/javascript">

var link = "https://en.wikipedia.org/wiki/The_Most_Interesting_Man_in_the_World";

d3.select("body").selectAll("div").append("text").text("The most interesting man in the world");

// is there any way to make 'man' link to 'wiki_link' or perform some other operation?

</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

是的,虽然您需要以适合d3的方式格式化数据,但这是可能的。

Demo

var data = [{ text: 'The most interesting ', href: false },
            { text: 'man', href: 'https://en.wikipedia.org/wiki/The_Most_Interesting_Man_in_the_World' },
            { text: ' in the world', href: false}];

var text = d3.select("body").selectAll("div").append("text");

text.selectAll('tspan')
  .data(data)
  .enter()
  .append('tspan')
  .html(function (d) { 
     return d.href 
       ? '<a href=' + encodeURI(d.href) + '>' + d.text + '</a>' 
       : d.text; 
   });
相关问题