hasClass在我的js代码中不起作用? [英] hasClass doesn't work in my js code?
问题描述
我想在以下代码中使用hasClass
,但这对我不起作用,请在jsfiddle中查看我的演示并告诉我,我该怎么做?
I want to use hasClass
in the following code, but that doesn't work for me, please see my demo in jsfiddle and tell me, what do I do wrong?
<span>
<input type="text" name="relation" class="IdRelation">
</span>
if ($('span').hasClass('IdRelation')) {
alert("ok");
}
推荐答案
解决方案
该类位于<span>
子级(<input>
)上,因此将其添加到jQuery选择器中:$('span input')
.
Solution
The class is on the <span>
child, an <input>
, so add it in the jQuery selector : $('span input')
.
if ($('span input').hasClass('IdRelation')) {
alert('ok');
}
尝试演示.
根据jQuery文档,$('span input')
是 后代选择器 :
Accorting to jQuery documentation, $('span input')
is a descendant selector :
选择作为给定祖先的后代的所有元素.
Selects all elements that are descendants of a given ancestor.
您也可以使用$('span > input')
.这是 子选择器 :
You could also use $('span > input')
. It is a child selector :
选择父"指定的元素的子"指定的所有直接子元素.
Selects all direct child elements specified by "child" of elements specified by "parent".
两种情况都对您有利,因为input
是<span>
的直接子代.
Both are good in your situation, because the input
is a direct child of the <span>
.
如果您的代码是:
<div>
<form>
<input type="text" name="relation" class="IdRelation">
</form>
</div>
解决方案将为$('div input')
或$('div > form > input')
.
这篇关于hasClass在我的js代码中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!