首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >svg路径上的jQuery包装隐藏路径。

svg路径上的jQuery包装隐藏路径。
EN

Stack Overflow用户
提问于 2018-05-28 09:25:28
回答 1查看 255关注 0票数 0

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

代码语言:javascript
复制
$('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());
  });

希望有人能帮我。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-29 08:15:17

SVG <a>元素不同于<a>元素。它们有一个不同的名称空间。您的jQuery正在插入一个<a>元素,就SVG呈现而言,它是一个无效的元素。因此,它和它的内容( <path>)一起被忽略。

通常,不能用jQuery添加SVG元素。它只为HTML设计。因此,您需要使用另一种方法--比如vanilla。

代码语言:javascript
复制
$('.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);
}
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50563073

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档