将路径元素包装在锚标记中

Wrapping path elements in an anchor tag

本文关键字:路径 元素 包装      更新时间:2023-09-26

我正在尝试使我在 d3 中的圆环图中的<text><path>元素可点击,但遇到了一些问题。 这是我正在使用的代码:

        var g = svg.append('g')
            .attr('transform', 'translate(' + width / 2 + ',' + ((height / 2)) + ')');
        var arcs = g.selectAll('path');            
        arcs = arcs.data(pie(formattedData));
        arcs.exit().remove();
        arcs.enter().append('path')
            .style('stroke', 'white')
            .attr('fill', function (d, i) { return color(i) });
        arcs.attr('d', arc);
        arcs.append("text")
            .attr("transform", function (d) { return "translate(" + labelArc.centroid(d) + ")"; })
            .attr("dy", "0em")
            .attr("style", "font-size: 1.5em;")
            .attr("fill", "white")
            .text(function (d) { return d.value; })

我可以通过直接在开发工具中编辑 DOM 来在<path><text>元素周围添加 <a> 标记,但我也无法.wrap()或更改代码以使用它:

.append("a").attr("href", "http://wwww.gooogle.com")

我错过了什么?

您只需将

a 元素附加到 pathtext 元素之前即可执行此操作:

arcs.enter()
  .append('a')
    .attr('href', 'http://www.google.com')
  .append('path')
    .style('stroke', 'white')
    .attr('fill', function (d, i) { return color(i) })
    .attr('d', arc);

请参阅 https://jsfiddle.net/m4mj8u7L/1/

看起来你正在尝试用jQuery编辑SVG DOM元素。如果是这样,不久前我自己也遇到了这个问题。SVG 元素的处理方式与普通 HTML 元素不同,因此许多 jQuery 函数不会影响它们。不过,您可以使用一些替代语法来解决这些限制。看看这个答案,寻找一些方向。