gpt4 book ai didi

javascript - jQuery SVG,为什么我不能添加类?

转载 作者:行者123 更新时间:2023-11-28 09:18:31 24 4
gpt4 key购买 nike

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

最佳答案

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

关于javascript - jQuery SVG,为什么我不能添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com