JQuery&操纵通过对象标签加载的SVG?

时间:2015-04-12 21:34:17

标签: javascript jquery svg

我已经通过对象块加载了一个SVG文档,我想以编程方式为每个组添加一个标题标记,但是我被卡住了。 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'))

任何人都可以建议将子元素添加到通过object标签加载的SVG的正确方法。我宁愿拥有JQuery的便利,但如果这不是一个选项,我有兴趣听取替代方案。

BTW我确实看过Raphael,但这似乎只允许操纵通过Raphael创建的SVG对象,因此在这种情况下不是一个可行的选项。

1 个答案:

答案 0 :(得分:0)

使用img标签调整这个类似问题的答案:

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

将src属性更改为数据,并将class =“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');
    });