对于SVG元素,jQuery .hasClass()方法失败 [英] jQuery .hasClass() method fails for SVG elements

查看:803
本文介绍了对于SVG元素,jQuery .hasClass()方法失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组SVG元素,它们的类 node link 。我的程序应该在悬停在任何SVG元素上时检测元素是否具有节点类或链接类。但是,由于某些原因, .hasClass()似乎不起作用:

 < $ c $> $(。node)。hover(function(evt){
console.log($(this).attr(class)); //返回node
console.log($(this).hasClass('node')); //返回false
},function(){console.log(Done);});

因此,我所在的元素有类 node ,但由于某些原因,实际的 code> .hasClass()失败。为什么是这样?它是否因SVG而失败?

解决方案

HTML元素的类属性在SVG中的含义不同。 / p>

  $(< b>< / b>)。addClass($(this).attr(class ))。hasClass(node)

或者

  /(^ | \s)节点(\s | $)/。test($(this).attr(class))

为SVG元素。



编辑。类似乎工作得很好(至少在IE9和FF中) http://jsfiddle.net/X6BPX/ 1 /



所以这个问题可能是以下几种情况的组合:语法错误,使用过时的浏览器,使用过时的jQuery版本。

I have a set of SVG elements with the classes node and link. My program should detect whether an element has the node class or the link class upon hovering over any of the SVG elements. However, for some reason, the .hasClass() doesn't seem to work:

$(".node").hover(function(evt){
    console.log($(this).attr("class")); //returns "node"
    console.log($(this).hasClass('node')); //returns false
}, function(){console.log("Done");});

So the element I hovered on has the class node, and jQuery detects that too, as shown by console.log($(this).attr("class"));, but for some reason the actual .hasClass() fails. Why is this? Is it failing because of the SVG?

解决方案

The class attribute for HTML element doesn't have the same meaning in SVG.

$("<b></b>").addClass($(this).attr("class")).hasClass("node")

Or

/(^|\s)node(\s|$)/.test($(this).attr("class"))

for SVG elements.

EDIT .hasClass seems to work just fine (at least in IE9 and FF) http://jsfiddle.net/X6BPX/1/

So the problem could be any combination of the following: a syntax error, using an outdated browser, using an outdated version of jQuery.

这篇关于对于SVG元素,jQuery .hasClass()方法失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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