admin管理员组文章数量:1391975
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");
}
DEMO
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");
}
DEMO
Share Improve this question edited Jul 26, 2012 at 12:27 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Jul 26, 2012 at 12:23 jennifer Joliejennifer Jolie 7276 gold badges17 silver badges31 bronze badges 3-
2
It kind of looks like you're using
IdRelation
as a unique marker (obviously just a guess based on your markup). If so you might want to consider usingid="relation"
instead and select it using$("#relation")
. – Vala Commented Jul 26, 2012 at 12:29 -
1
Especially with the prefix
Id
which does not sound like it would be a class – mplungjan Commented Jul 26, 2012 at 12:36 -
1
there is no
span
with a classIdRelation
, did you meaninput
? – jbabey Commented Jul 26, 2012 at 12:39
2 Answers
Reset to default 11It is not the <span>
element that exposes the IdRelation
class, but its <input>
child. Try:
if ($("span input").hasClass("IdRelation")) {
alert("ok");
}
Or maybe, depending on your actual markup:
if ($("span > input").hasClass("IdRelation")) {
alert("ok");
}
The selector in the first code snippet will match all <input>
elements that are descendants of a <span>
element, whereas the selector in the second snippet will match all <input>
elements that are direct children of a <span>
element. Both will match the <input>
element in your sample markup.
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');
}
Try the Demo.
A bit of explanation
Accorting to jQuery documentation, $('span input')
is a descendant selector :
Selects all elements that are descendants of a given ancestor.
You could also use $('span > input')
. It is a child selector :
Selects all direct child elements specified by "child" of elements specified by "parent".
Both are good in your situation, because the input
is a direct child of the <span>
.
If your code was :
<div>
<form>
<input type="text" name="relation" class="IdRelation">
</form>
</div>
The solution will be $('div input')
or $('div > form > input')
.
本文标签: javascripthasClass doesn39t work in my js codeStack Overflow
版权声明:本文标题:javascript - hasClass doesn't work in my js code? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744687222a2619775.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论