jQuery textpath svg 元素有问题

jQuery having issues with textpath svg elements

我在我的项目中使用 SVG 并希望 toggleClassjQuery[=单击 textpath 元素上的 28=]。

所以我在想:

$("text#names > textpath").click(function() {
    $(this).toggleClass("newClass");
});

在 HTML 来源:

<text id="names" class="clickthrough">
    <textpath class="zoom1" href="#text1" font-size="12.1"></textpath>
    <textpath ... </textpath>
</text>

但什么也没发生。如果我这样做 $("text#names"),我会得到 class 点击率 。所以它正在工作,只是文本路径可能不为 jQuery 所知。所以我找到了 http://keith-wood.name/svgref.html 但在使用它之前,我想确定我的情况是否真的需要它。

jQuery 的 .class 不适用于 SVG 元素,您必须改用 attr

$("text#names > textpath").click(function() {
  $(this).attr("class", function(_, val){
    return (val.indexOf("newClass")+1) ? val.replace(" newClass","") : val+" newClass";
  });
});

查看 the jsFiddle demo