javascript - 使用 Jquery 查找下一个特定类并检查它是否有另一个类

标签 javascript jquery

使用 jQuery 我想找到下一个类,检查它是否有另一个类,如果有,则更改当前项目。

例子:

<div class="item itemA"></div> // only change this background to red
<div class="item itemA"></div>
<div class="item itemB"></div>
<div class="OtherClass"></div>
<div class="item itemA"></div>

我想检查下一个类“item”(可能在其他一些 html 之后)是否也有类“itemA”,如果是,则更改当前的 itemA。例如,将背景更改为红色。

在上面的例子中只有第一个 DIV 会改变,因为下一个类“item”也有类“itemA”。第二类“itemA”的下一个类“item”是“itemB”,所以这个 DIV 不应该改变。

我尝试了 .next() 函数,但没有成功。主要是因为类之间可能还有其他 HTML。所以它真的需要找到下一个“item”类,检查那个“item”是否也有类“itemA”并改变之前的那个。

欢迎任何帮助!

最佳答案

嗨,鲍勃,我希望你正在寻找如下解决方案

var counter = 0;    
var prevElement;

//traverse all the div's
$.each($('body div'), function(){

  //if div has class "item" as first class in class list 
  if( $(this).attr('class').split(' ')[0] == "item") {

    //if div has class "itemA" as second class in class list 
    if("itemA" == $(this).attr('class').split(' ')[1]) {
        if(counter == 1 ) {

        //change color
        prevElement.addClass('redColor');
      } 
      counter = 1;
      prevElement = $(this);
    } 
  }
});

请查看 Fiddle https://jsfiddle.net/Prakash_Thete/a5y4gkzg/2/

关于javascript - 使用 Jquery 查找下一个特定类并检查它是否有另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36667902/

相关文章:

php - 使用 JQuery 和 Bootstrap 切换按钮 - 如何在切换后更改非事件类

javascript - iframe 加载事件

javascript - 我的代码只能运行一次

javascript - 想要将所有导航选项卡收集到页面缩放上的图标中

jquery - JQuery Mobile Page如何添加 flex 弹跳效果?

javascript - 如何使用 jquery 获取 Mvc Telerik Grid 中的行值

javascript - 设置触发器以在每月的最后一个小时运行函数

javascript - 我的渲染方法做错了什么,导致我收到 "Invariant Violation"错误?

javascript - 使用 float 新添加的数据点的平滑动画

javascript - 如何按 z-index 对这些 Canvas 元素进行排序?