2015-04-12 51 views
2

我已經通過一個對象塊加載了一個SVG文檔,我希望以編程的方式爲每個組添加一個標題標籤,但是我被卡住了。 SVG的裝載如下:JQuery&操縱通過對象標籤加載的SVG?

<object data="International_Telecommunication_Union_region.svg" type="image/svg+xml" id="worldMap"> 
</object> 

然後我試圖讓組元素之一,如下所示(使用JQuery 1.11.2):

$('g .landxx .BR') 

但這返回一個空列表。然而,如果我這樣做,我得到在Chrome的控制檯上顯示的元素:

console.log($('g .landxx .BR')) 

任何人都可以建議增加一個子元素,通過對象標籤加載的SVG的正確途徑。我寧願有JQuery的便利,但如果這不是一個選項,我有興趣聽到替代方案。

順便說一句我看過拉斐爾,但這似乎只允許操縱通過Raphael創建的SVG對象,所以在這種情況下不是可行的選項。

+0

當你的jQuery代碼被調用時,你確定SVG是完全加載的嗎? – arjabbar

+0

您可能會使用錯誤的文檔,請參閱http://stackoverflow.com/questions/6316979/selecting-an-element-in-iframe-jquery(對象和iframe應該表現得非常相似)。無論如何,只需從'object'元素中獲取'contentDocument'並使用它,這裏是一個示例http://xn--dahlstrm-t4a.net/svg/html/get-embedded-svg-document-script.html。 –

+0

@arjabbar一旦圖像完全加載並且行爲相同,我會從控制檯嘗試相同的操作。 –

回答

0

答案就適應使用img標籤這種類似的問題:

How to change color of SVG image using CSS (jQuery SVG image replacement)?

變化src屬性數據並添加類=「SVG」你的對象標記。 我測試了它,我能夠改變與CSS的填充和描邊,應該與jquery工作得很好。

jQuery('object#worldMap').each(function(){ 
     var $img = jQuery(this); 
     var imgID = $img.attr('id'); 
     var imgClass = $img.attr('class'); 
     var imgURL = $img.attr('data'); 

     jQuery.get(imgURL, function(data) { 
      // Get the SVG tag, ignore the rest 
      var $svg = jQuery(data).find('svg'); 

      // Add replaced image's ID to the new SVG 
      if(typeof imgID !== 'undefined') { 
       $svg = $svg.attr('id', imgID); 
      } 
      // Add replaced image's classes to the new SVG 
      if(typeof imgClass !== 'undefined') { 
       $svg = $svg.attr('class', imgClass+' replaced-svg'); 
      } 

      // Remove any invalid XML tags as per http://validator.w3.org 
      $svg = $svg.removeAttr('xmlns:a'); 

      // Replace image with new SVG 
      $img.replaceWith($svg); 

     }, 'xml'); 
    });