2016-01-20 74 views
0

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

<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> 
    ......... 

这里是JS代码SVG元素来获取和创建<title>标签,现在的代码通过name attr的<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这是name属于g id="id3"。我认为这是关于.each()的回调。但我无法解决..我怎样才能把<g>的每个name attr作为文本值<title>?谢谢。

编辑PS。 svg文件从另一个平台导出,导出程序的源代码不可用于在那里定义<title>

回答

1

问题是,你在循环遍历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 
}); 
+0

感谢您的回复。其实我以前试过这个方法,但是在标签里写了“名字”。以下是根据您的建议标记之一 ' 1AC5' – yalcinm1

+0

请参阅我的更新回答。设置title属性的正确方法是$(this).attr(“title”,c)'。 – adilapapaya

+0

谢谢。已更新的答案现在在标记中增加了另一个属性,“name”和“title”属性具有相同的值。我认为让它们保持在标记内不允许将它显示为带有svg文件的工具提示。但是,谢谢你的帮助。请让我知道任何建议。 – yalcinm1

相关问题