我使用jQuery SVG。我不能向对象添加或删除类。有人知道我的错误吗?

SVG:

<rect class="jimmy" id="p5" x="200" y="200" width="100" height="100" />

jQuery不会添加类:

$(".jimmy").click(function() {
    $(this).addClass("clicked");
});

我知道SVG和jQuery一起工作很好,因为我可以瞄准对象,并在点击时发出警报:

$(".jimmy").click(function() {
    alert('Handler for .click() called.');
});

当前回答

有元素。用于HTML和SVG元素的DOM API中的classList。不需要jQuery SVG插件,甚至jQuery。

$(".jimmy").click(function() {
    this.classList.add("clicked");
});

其他回答

加载jquery.svg.js后,必须加载这个文件:http://keith-wood.name/js/jquery.svgdom.js。

来源:http://keith-wood.name/svg.html dom

工作示例:http://jsfiddle.net/74RbC/99/

编辑2016:阅读下面两个答案。

JQuery 3修复了潜在的问题 Vanilla JS: element.classList.add('newclass')适用于现代浏览器


JQuery(小于3)不能向SVG添加类。

.attr()与SVG一起工作,所以如果你想依赖jQuery:

// Instead of .addClass("newclass")
$("#item").attr("class", "oldclass newclass");
// Instead of .removeClass("newclass")
$("#item").attr("class", "oldclass");

如果你不想依赖jQuery:

var element = document.getElementById("item");
// Instead of .addClass("newclass")
element.setAttribute("class", "oldclass newclass");
// Instead of .removeClass("newclass")
element.setAttribute("class", "oldclass");

只需将缺失的原型构造函数添加到所有SVG节点:

SVGElement.prototype.hasClass = function (className) {
  return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
};

SVGElement.prototype.addClass = function (className) { 
  if (!this.hasClass(className)) {
    this.setAttribute('class', this.getAttribute('class') + ' ' + className);
  }
};

SVGElement.prototype.removeClass = function (className) {
  var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
  if (this.hasClass(className)) {
    this.setAttribute('class', removedClass);
  }
};

然后你可以这样使用它,而不需要jQuery:

this.addClass('clicked');

this.removeClass('clicked');

所有功劳都归功于托德·莫托。

我使用Snap.svg向SVG添加一个类。

var jimmy = Snap(" .jimmy ")

jimmy.addClass("exampleClass");

http://snapsvg.io/docs/#Element.addClass

有元素。用于HTML和SVG元素的DOM API中的classList。不需要jQuery SVG插件,甚至jQuery。

$(".jimmy").click(function() {
    this.classList.add("clicked");
});