SVG <title> 文本循环获取数组的最后一个元素
SVG <title> text loop gets the last element of array
我在 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
});
相关文章:
- JavaScript数组包含一个值
- 使用事件更改数组的一个元素
- 从 javascript 数组创建一个 Jquery 数组
- 使用javascript匹配字符串中数组的一个元素
- Angular2从数组创建一个列表
- 在Javascript数组或一个对象中存储多个数据所需的Tweak
- 你能给被劫持的JavaScript数组添加一个函数吗
- 从带有循环的数组中一个接一个地在画布上绘制形状
- 将图像数组从一个窗口传递到另一个窗口,并在javascript的新窗口中显示图像
- 使用拆分字符串的数组创建一个对象
- 多维数组 - 创建一个表
- Javascript使用map从一维数组创建一个二维数组
- 角度范围变量中的数组只有一个成员
- 将数组从一个函数传递到另一个函数
- 如何推送到实际对象的数组最后状态,清除它并像新对象一样单独编辑
- 将 php 数组发送到 jquery ajax 并从该数组创建一个 each 循环
- 角度.js:如何更新数组的一个项目
- 数组最后一个单元格中不需要的对象
- Setter 函数用于动态访问数组中的字段,该数组是一个属性
- 可以使用Array.splice()通过在数组最后一个元素之外的索引处添加元素来创建稀疏数组吗