javascript - 点击时流星改变背景颜色
问题描述
Meteor 中的此代码需要在单击时将背景颜色更改为黄色,在再次单击时将背景颜色更改为白色,我在阅读其他解决方案后尝试了几种方法,但无法使其正常工作。
如果它是白色的,如何将颜色更改为黄色,如果它是黄色的,如何将其更改为白色。稍后我还需要在条件语句中编写其他内容。
HTML 是:
<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></P>
谢谢
'click .toggleBackground': (e) => {
//$(e.target).addClass('yellow'); // tried with css file for no avail
console.log($(e.target).css("background-color"));
//tried === rgba(255, 255, 0) instead of yellow for no avail
if($(e.target).css('background-color') === 'yellow'){ //<<< never true
console.log('already yellow'); //<<< never called
$(e.target).css('background-color', 'white');
} else {
console.log('will make yellow');
$(e.target).css('background-color', 'yellow');
}
}
.white{
background-color: #FFFFFF
}
.red{
background-color: yellow
}
解决方案
请检查下面的代码,这对你有用。在这里,我使用类来检查当前应用于元素的类,并在此基础上切换类,以便当存在黄色时,它将删除该类并添加白色类,反之亦然。
$(".toggleBackground").click(
function () {
if($(this).hasClass("red")){
$(this).removeClass("red");
$(this).addClass("white");
}
else{
$(this).addClass("red");
$(this).removeClass("white");
}
}
);
.white{
background-color: #FFFFFF
}
.red{
background-color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>{{car.carID}} <strong class="toggleBackground">{{car.plate}}</strong></p>
推荐阅读
- typescript - 在 Typescript 中创建自定义类型的大型项目列表
- elasticsearch - ELASTICSEARCH - 在没有预定义日期字段的情况下自动包含日期
- java - 如何将 MULE VM 参数添加到 Docker 容器?
- javascript - 尝试通过 HTTP 将 JSON 有效负载发布到 localhost 时出现 NetworkError
- html - 反应形式的多个 FormArrays
- r - 如何在R中使用正则表达式删除+
- classification - 为 CGAL 分类划定网格训练
- c - 在 Windows (MinGW) 中使用 make 编译 C
- r - 将密度图覆盖到 ggplot2 中的每个现有分面包裹的密度图?
- powershell - 当有两个参数时,删除powershell中的重复项