[英]hasClass doesn't work in my js code?
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? 我想在以下代码中使用
hasClass
,但这对我不起作用,请在jsfiddle中查看我的演示并告诉我,我该怎么做?
<span>
<input type="text" name="relation" class="IdRelation">
</span>
if ($('span').hasClass('IdRelation')) {
alert("ok");
}
It is not the <span>
element that exposes the IdRelation
class, but its <input>
child. 公开
IdRelation
类的不是<span>
元素,而是它的<input>
子元素。 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. 第一个代码段中的选择器将匹配作为
<span>
元素后代的所有<input>
元素,而第二个代码段中的选择器将匹配作为<span>
元素的直接子代的所有<input>
元素。 Both will match the <input>
element in your sample markup. 两者都将与示例标记中的
<input>
元素匹配。
The class is on the <span>
child, an <input>
, so add it in the jQuery selector : $('span input')
. 该类位于
<span>
子项中,即<input>
,因此将其添加到jQuery选择器中: $('span input')
。
if ($('span input').hasClass('IdRelation')) {
alert('ok');
}
Accorting to jQuery documentation, $('span input')
is a descendant selector : 根据jQuery文档,
$('span input')
是后代选择器 :
Selects all elements that are descendants of a given ancestor.
选择作为给定祖先的后代的所有元素。
You could also use $('span > input')
. 您也可以使用
$('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>
. 两者都适合您的情况,因为
input
是<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')
. 解决方案将是
$('div input')
或$('div > form > input')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.