Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 检查除第一个元素外的所有元素是否都有特定的类_Jquery - Fatal编程技术网

Jquery 检查除第一个元素外的所有元素是否都有特定的类

Jquery 检查除第一个元素外的所有元素是否都有特定的类,jquery,Jquery,我想检查容器的所有元素(第一个除外)是否都有特定的类。如果是这种情况,容器应该得到类“ok”;否则它应该得到类“notok” 在本例中,我想检查容器“content”的所有“something”元素是否都具有类“anything”。第一个元素应该被忽略 <div class="content"> // will get the class "ok" <div class="something"></div> <div class="som

我想检查容器的所有元素(第一个除外)是否都有特定的类。如果是这种情况,容器应该得到类“ok”;否则它应该得到类“notok”

在本例中,我想检查容器“content”的所有“something”元素是否都具有类“anything”。第一个元素应该被忽略

<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>
//将获得类“ok”
上面的应该可以

虽然这个不应该是正确的,因为有一个元素缺少“anyting”类:

//将获得类“notok”
我试着用
each()
解决这个问题,但由于第一个元素出现异常,我失败了…

试试这个:

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;
}

您仍然可以使用
.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
});
工作演示:


如果第一个元素具有anything类是否可以?只需正确理解即可。如果我想将类“ok”添加到主容器的头中,我必须如何修改脚本。请看一下这个:
$('.content').children().each(function(i) {
   if (i == 0) return true;
   //it will only reach this point on every child except the first
});
$('div.content').filter(function () {
    return $('div:gt(0).something.anything', this).length == $('div:gt(0)', this).length
}).addClass('ok')