检查是否有匹配的类名,然后做些什么

checking to have the matched class names and do something

本文关键字:然后 做些什么 是否 检查      更新时间:2024-05-05

我想检查是否有正在动态生成的具有匹配className的元素,并在这种情况下应用一些代码:

比如:

<div class="c red"></div>
<div class="c green"></div>
<div class="c red"></div>
<div class="c yellow"></div>
<div class="c red"></div>

我想检查那些类为"red"的标签,并对它们应用一些东西但请记住,我不能直接调用$(".red")元素,因为每次加载页面时它可能会发生变化,下次会变成不同的颜色,所以我想要一个通用的解决方案来检查文档中的类名是否匹配

使用jQuery:

$('div.c').each(function(_, div) {
    if( $(div).hasClass( 'red' ) ) {
        // this div node has a class called 'red'
    }
});

您可以使用.hasClass().is()来确定。请注意,当使用.is()时,您需要使用前导点来限定字符串,如'.red'

使用香草Javascript:

[].forEach.call( document.querySelectorAll( 'div.c' ), function( div ) {
    if( div.classList.contains( 'red' ) ) {
        // this div node has a class called 'red'
    }
});
相关文章: