首页 > 解决方案 > 如果类不存在,jQuery 更改 CSS 值

问题描述

我正在尝试创建一个 lille 脚本来浏览我的页面并检查一个类是否存在于任何<div>. 如果类在场,则不会有任何动作。

它会寻找class="blue",如果找到它就什么也不做。如果它不 fintclass="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>

标签: javascriptjqueryhtmlcss

解决方案


一个班轮... :)

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

基本上,您希望如果有蓝色,.yellow则为绿色。否则,它会保持黄色。

您可以通过转到小提琴 (^above) 并取消注释蓝色来查看当蓝色存在时会发生什么。

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>


推荐阅读