gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:41:40 25 4
gpt4 key购买 nike

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com