我想检查一个容器的所有元素(第一个元素除外)是否都有某个类。如果是这种情况,容器应该得到类" ok&#34 ;;否则它应该得到课程" notok"。
在这个例子中,我想检查一下"是什么"容器的元素"内容"有类"什么"。第一个元素应该被忽略。
<div class="content"> // will get the class "ok"
<div class="something"></div>
<div class="something anything"></div>
<div class="something anything"></div>
<div class="something anything"></div>
<div class="something anything"></div>
</div>
上面应该没问题。
虽然这个不应该没问题,因为有一个元素缺少&#34;任何&#34; -class:
<div class="content"> // will get the class "notok"
<div class="something"></div>
<div class="something anything"></div>
<div class="something anything"></div>
<div class="something"></div>
<div class="something anything"></div>
</div>
我试图用each()
来解决这个问题,但由于第一个元素的异常而导致我失败了......
答案 0 :(得分:1)
试试这个:
function myFunction() {
var ret = "ok";
// Get all divs of content except the first
$(".content div:gt(0)").each(function() {
if (!$(this).hasClass("anything")) {
ret = "notok";
return false;
}
});
return ret;
}
答案 1 :(得分:1)
$('div.content').filter(function () {
return $('div:gt(0).something.anything', this).length == $('div:gt(0)', this).length
}).addClass('ok')
<强> jsFiddle example 强>
答案 2 :(得分:0)
您仍然可以使用.each()
来解决此问题。
要选择元素的所有子元素,请使用.children()
。调用.each(function(i){})
将迭代每个元素并使用迭代器,然后您可以检查它是否为零并继续循环。
$('.content').children().each(function(i) {
if (i == 0) return true;
//it will only reach this point on every child except the first
});