![](/img/trans.png)
[英]Change CSS attribute value present in two different rules by adding a class
[英]jQuery Change CSS value if class not present
我正在尝试创建一个里尔脚本来浏览我的页面,并检查任何<div>
是否存在类。 如果存在该类,则将不执行任何操作。
它将查找class="blue"
,如果找到它,将不执行任何操作。 如果没有找到class="blue"
,它将更改class="yellow"
背景颜色。 它的作用是改变class="yellow"
的背景颜色,无论如何。 怎么了?
$("div").each(function() { if (jQuery(this).attr('class') != undefined && jQuery(this).hasClass('blue')) {} else { $('.yellow').css('background', 'green') } });
.blue { background: blue; width: 100px; height: 100px; } .red { background: red; width: 100px; height: 100px; } .yellow { background: yellow; width: 100px; height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="blue"> Blue </div> <div class="red"> Red </div> <div class="yellow"> Yellow </div>
一个班轮... :)
http://jsfiddle.net/yak613/bcgajp6q/
基本上,您希望如果有蓝色,则.yellow
是绿色。 否则,它将保持黄色。
您可以通过移到小提琴(^上方)并取消对蓝色的注释来查看蓝色在那里时的情况。
if(!$(".blue").length) $(".yellow").css('background-color', 'green');
.blue { background: blue; width: 100px; height: 100px; } .red { background: red; width: 100px; height: 100px; } .yellow { background: yellow; width: 100px; height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- <div class="blue"> Blue </div> --> <div class="red"> Red </div> <div class="yellow"> Yellow </div>
您需要做的就是简单地检查目标元素是否没有.blue
类(以及if (!$(this).hasClass('blue'))
)。
可以在以下内容中看到:
$("div").each(function() { if (!$(this).hasClass('blue')) { $('.yellow').css('background', 'green') } });
.blue { background: blue; width: 100px; height: 100px; } .red { background: red; width: 100px; height: 100px; } .yellow { background: yellow; width: 100px; height: 100px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="blue"> Blue </div> <div class="red"> Red </div> <div class="yellow"> Yellow </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.