我使用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");
基于以上答案,我创建了以下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;
};