SVG <title> 文本循环获取数组的最后一个元素

SVG <title> text loop gets the last element of array

本文关键字:数组 最后一个 获取 元素 文本 title SVG 循环      更新时间:2023-09-26

我在 svg 文件的 <g> 标签下添加了一个<title>标签。现在我需要在 <title> 标签中放置一些文本,以便稍后制作鼠标悬停工具提示。我将放入<title>的文本来自第二个g标签的name属性。我正在做一个循环,但它总是将数组的最后一个元素写入<title>.以下是 svg 文件的基本结构:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="product123">
    <g id="id1" name="1AC1">
        <path style="stroke:black; fill:none;" d="/some path"/>
        <title>//text comes from name attr of "g"</title> //tags added with the code below
    </g>
    <g id="id2" name="1AC2">
        <path style="stroke:black; fill:none;" d="/some path"/>
        <title>//text comes from name attr of "g"</title>
    </g>
    <g id="id3" name="1AC3">
        <path style="stroke:black; fill:none;" d="/some path"/>
        <title>//text comes from name attr of "g"</title>
    </g>
    .........

这是获取 SVG 元素并创建 <title> 标签并传递name属性的 JS 代码<g>

var $svg = jQuery(data).find('svg');
$('g>g').each(function() {
    var $input = $( this );
    var c = function () {
        return $input.attr("name") //get the "name" attributes and store in var c
    };
    $(this).append("<title/>"); //create <title> tag
    $('g>g>title').each(function() { //I am in <title> tag
       $(this).text(c) //pass all "c" as text to each <title>
       });
    });
});

现在使用上面的代码,我可以放置<title>标签,但每个<title>返回的文本都是相同的。并且值始终是1AC3这是g id="id3"name吸引力。我认为这是关于.each()的回调。但我无法解决..如何将<g>的每个name属性作为<title>的文本值?谢谢。

编辑附言。svg 文件是从另一个平台导出的,导出器的源代码不可用于定义<title>

问题是您循环遍历g>g两次,并在第二次运行时覆盖原始值。

var $svg = jQuery(data).find('svg');
$('g>g').each(function() {
    var $input = $( this );
    var c = function () {
        return $input.attr("name") //get the "name" attributes and store in var c
    };

    /*
    $(this).append("<title/>"); //create <title> tag
    // This part here is over-writing your previous title.
    $('g>g>title').each(function() { //I am in <title> tag
       $(this).text(c) //pass all "c" as text to each <title>
       });
    });
    */
    // Use this instead to set the title on the current
    // element. 
    $(this).attr("title", c); // correct way to set the title attribute
});