2016-01-20 72 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

相關問題