我有一个页面设置,其中一些div具有类.w2
,而另一些则没有,因为我需要这些项具有不同的图像大小。所以我一直在四处寻找,看看我可以用什么来检查是否应用了类并找到了class_exists
函数。
所以我先做了一个小测试,看看它是如何工作的,但它总是返回false
。即使我试图查看页面是否应用了类item
(每个div元素都这样做),这也是一样的,但它仍然返回false
。
<div class="item w2">
<?php
if (class_exists('w2')) {
echo "The class is applied!";
} else {
echo "This class is not applied";
}
?>
<div>
谢谢你对此的任何建议。
/*编辑*/
我一直在考虑这个问题,实际上我不需要在其他每个div中添加另一个类。我只需要选择其他每个div。所以我想我可以使用:nth child(even)选择器。使用下面的代码进行尝试是可行的,但我想知道是否有更干净的方式来编写标记?
jQuery(function() {
if ($("#grid .item:nth-child(even)")) {
$(".item:nth-child(even) .figure h2").css('background', 'red');
} else {
$(".figure h2").css('background', 'blue');
}
});
感谢您在这篇文章中提供的所有有用的答案。
PHP class_exists
函数用于检查类(在OOP意义上)是否存在,而不是客户端上的CSS类。事实上,PHP严格来说是服务器端的,在生成HTML之后,它对任何HTML都一无所知。
要做您需要的事情,您可以使用jQuery,如下所示:
<div class="item w2">
<script type="text/javascript">
$(function() {
if ($('.w2').length) {
console.log('The class is applied!');
}
else {
console.log('The class is not applied');
}
});
</script>
更新
在回答您编辑中的第二个问题时。。。。
$( "div:odd" ).css( "background-color", "red" );
$( "div:even" ).css( "background-color", "blue" );
您正在检查是否存在PHP类,而不是CSS类。您希望使用jQuery来完成此操作。
if ($(".w2").length > 0) {
alert('class exists');
$(".w2").each(function() {
//perform some logic on found elements
$(this).doStuff();
});
} else {
alert('class does not exist');
}