jQuery SVG,为什么我不能添加类? [英] jQuery SVG, why can't I addClass?

查看:25
本文介绍了jQuery SVG,为什么我不能添加类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery SVG.我无法向对象添加或删除类.有人知道我的错误吗?

I am using jQuery SVG. I can't add or remove a class to an object. Anyone know my mistake?

SVG:

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

不会添加类的jQuery:

The jQuery that won't add the class:

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

我知道 SVG 和 jQuery 可以很好地协同工作,因为我可以定位对象并在单击时发出警报:

I know the SVG and jQuery are working together fine because I can target the object and fire an alert when it's clicked:

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

推荐答案

Edit 2016:阅读接下来的两个答案.

Edit 2016: read the next two answers.

  • JQuery 3 修复了根本问题
  • Vanilla JS:element.classList.add('newclass') 适用于现代浏览器
  • JQuery 3 fixes the underlying issue
  • Vanilla JS: element.classList.add('newclass') works in modern browsers

JQuery(少于 3 个)无法向 SVG 添加类.

JQuery (less than 3) can't add a class to an SVG.

.attr() 适用于 SVG,因此如果您想依赖 jQuery:

.attr() works with SVG, so if you want to depend on jQuery:

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

如果你不想依赖 jQuery:

And if you don't want to depend on jQuery:

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

这篇关于jQuery SVG,为什么我不能添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆