我使用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.');
});

当前回答

我在我的项目中写了这个,它很有效……可能,)

$.fn.addSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        if(attr.indexOf(className) < 0) {
            $(this).attr('class', attr+' '+className+ ' ')
        }
    })
};    

$.fn.removeSvgClass = function(className) {

    var attr
    this.each(function() {
        attr = $(this).attr('class')
        attr = attr.replace(className , ' ')
        $(this).attr('class' , attr)
    })
};    

例子

$('path').addSvgClass('fillWithOrange')
$('path').removeSvgClass('fillWithOrange')

其他回答

编辑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");

或者,当JQ在某个地方出现问题时,只使用老派的DOM方法。

var myElement = $('#my_element')[0];
var myElClass = myElement.getAttribute('class').split(/\s+/g);
//splits class into an array based on 1+ white space characters

myElClass.push('new_class');

myElement.setAttribute('class', myElClass.join(' '));

//$(myElement) to return to JQ wrapper-land

了解DOM人。即使是在2016年的框架狂欢中,它也经常有所帮助。此外,如果您曾经听到有人将DOM与汇编进行比较,请替我踢他们一脚。

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

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

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

受到上述答案的启发,尤其是Sagar Gala,我创建了这个API。如果你不想或不能升级jquery版本,你可以使用它。

基于以上答案,我创建了以下API

/*
 * .addClassSVG(className)
 * Adds the specified class(es) to each of the set of matched SVG elements.
 */
$.fn.addClassSVG = function(className){
    $(this).attr('class', function(index, existingClassNames) {
        return ((existingClassNames !== undefined) ? (existingClassNames + ' ') : '') + className;
    });
    return this;
};

/*
 * .removeClassSVG(className)
 * Removes the specified class to each of the set of matched SVG elements.
 */
$.fn.removeClassSVG = function(className){
    $(this).attr('class', function(index, existingClassNames) {
        var re = new RegExp('\\b' + className + '\\b', 'g');
        return existingClassNames.replace(re, '');
    });
    return this;
};