svg路径上的jQuery wrap隐藏了路径

时间:2018-05-28 09:25:29

标签: jquery html svg anchor

我正在尝试将svg路径包装到HTML锚元素中。问题是,包装已完成,但svg路径不再显示在页面上。

$('svg-path').each(function() {
    var li_name = $(this).data("name");
    $(this).wrap($('<a xlink:href=""></a>'));
    $(this).parent().attr("xlink:href", $(`.linker-${li_name}`).text());
  });

希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

SVG <a>元素与HTML <a>元素不同。它们具有不同的命名空间。你的jQuery正在插入一个HTML <a>元素,就SVG渲染而言,它是一个无效的元素。因此它被忽略,连同其内容(<path>)。

通常,您无法使用jQuery添加SVG元素。它仅适用于HTML。所以你需要使用另一种方法 - 比如vanilla JS。

&#13;
&#13;
$('.svg-path').each(function() {
    var li_name = $(this).data("name");
    wrapSvgLink(this, li_name);
});


function wrapSvgLink(elem, url) {
  // Create an SVG <a> element
  var a = document.createElementNS(elem.namespaceURI, "a");
  // Add the xlink:href attribute
  a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", url);
  // Insert the new <a> element into the DOM just before our path
  elem.parentNode.insertBefore(a, elem);
  // Move the path so it is a child of the <a> element
  a.appendChild(elem);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg>
  <path class="svg-path" d="M 50,50 L 250,50 L 150,100 Z" data-name="foobar"/>
</svg>
&#13;
&#13;
&#13;