在svg路径元素上添加类

Nav*_*n S 7 html jquery svg

在我的项目中,我有一个SVG世界地图,其中包含不同id和一类的不同路径map-path.对于每个国家/地区,单击我想在每个路径上添加类.我的HTML是这样的:

<svg viewBox="">
    <path id="map_1" class="map-path" ......>
    <path id="map_2" class="map-path" ......>
    <path id="map_3" class="map-path" ......>
    <path id="map_4" class="map-path" ......>
    <!-- more <path /> elements... -->
</svg>
Run Code Online (Sandbox Code Playgroud)

Zak*_*rki 11

JQuery函数addClass()在这里不起作用,不能将类添加到SVG.

.attr()改为使用:

$('body').on('click','.map-path',function() {
    $(this).attr("class", "map-path newclass");
});
Run Code Online (Sandbox Code Playgroud)

您可以使用纯js解决方案setAttribute():

$('body').on('click','.map-path',function(e) {
    e.target.setAttribute("class", "map-path newclass");
});
Run Code Online (Sandbox Code Playgroud)

或者classList.add()在现代浏览器中使用它:

$('body').on('click','.map-path',function(e) {
    e.target.classList.add('newclass');
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.