jQuery wrap on svg path 隐藏路径

jQuery wrap on svg path hides the path

我正在尝试将 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());
  });

希望有人能帮助我。

SVG <a> 元素不同于 HTML <a> 元素。他们有不同的命名空间。您的 jQuery 正在插入一个 HTML <a> 元素,就 SVG 渲染而言,它是一个无效元素。所以它和它的内容(<path>)一起被忽略了。

通常,您不能使用 jQuery 添加 SVG 元素。它专为 HTML 设计。所以你将需要使用另一种方法 - 例如 vanilla JS。

$('.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);
}
<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>