javascript - 如果类不存在,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>
解决方案
一个班轮... :)
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>
推荐阅读
- javascript - 在 React 类组件中使用 ResizeObserver
- dictionary - map 指令未正确读取 nginx 入口控制器 kubernetes
- visual-studio - 我打破了 Visual Studio 代码覆盖率窗口。我如何解决它?
- java - 无法将 sam local api 连接到机密管理器
- sql - 比较数字
- javascript - 为什么在数组中移动数组会影响复制的(不是通过引用)数组,但移动整个初始数组不会?(Javascript)
- python - 如何将颜色图添加到条形图(例如 Viridis),垂直改变颜色?
- python - Tensorflow Python:多类标签的方法
- linux - 搜索一些模式并替换行中间的一些文本并忽略该行的最后一个字符
- r - 闪亮的进度条不适用于 mclapply()