jquery - svg路径上的jQuery wrap隐藏路径
问题描述
我正在尝试将 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>
推荐阅读
- ruby - 没有得到预期的答案
- php - .htaccess 将所有 url 重定向到 public/index.php,在 localhost 上没有反斜杠
- python - 如何计算数组中 3D 坐标中的距离
- javascript - 在项目中使用 tsconfig-paths?
- c# - 在 C# 中克隆图形的算法
- java - 组合集合组的正确方法
- revit-api - 如何获得房间边界的最长和最短边?
- excel - Excel for Mac 2019/2016/365 可能存在的错误:打印输出在某些情况下不起作用
- google-apps-script - 将可选查询参数添加到使用 Google Drive API 的评论编译器脚本
- c# - 从 2 个数据源将 2 个集合列表连接在一起,找到匹配项并循环遍历结果