简体   繁体   English

jQuery如果类不存在,则更改CSS值

[英]jQuery Change CSS value if class not present

I'm trying to create a lille script to go trough my page and check if a class is present in any <div> . 我正在尝试创建一个里尔脚本来浏览我的页面,并检查任何<div>是否存在类。 If the class is present then there will be no action. 如果存在该类,则将不执行任何操作。

It will look for class="blue" and if it find it it will do nothing. 它将查找class="blue" ,如果找到它,将不执行任何操作。 If it doesn't fint class="blue" it will change background color for class="yellow" . 如果没有找到class="blue" ,它将更改class="yellow"背景颜色。 What it does it change the background color for class="yellow" not matter what. 它的作用是改变class="yellow"的背景颜色,无论如何。 What is wrong? 怎么了?

 $("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> 

One liner... :) 一个班轮... :)

http://jsfiddle.net/yak613/bcgajp6q/ http://jsfiddle.net/yak613/bcgajp6q/

Basically, you want that if a blue is there, the .yellow is green. 基本上,您希望如果有蓝色,则.yellow是绿色。 Otherwise, it stays yellow. 否则,它将保持黄色。

You can see what happens when the blue is there by going to the fiddle (^above) and uncommenting the blue. 您可以通过移到小提琴(^上方)并取消对蓝色的注释来查看蓝色在那里时的情况。

 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> 

All you need to do is simply check if the target element doesn't have the .blue class (with if (!$(this).hasClass('blue')) ). 您需要做的就是简单地检查目标元素是否没有.blue类(以及if (!$(this).hasClass('blue')) )。

This can be seen in the following: 可以在以下内容中看到:

 $("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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM