JQuery初学者在这里。当我点击它们时,我试图让一组div从红色变成蓝色。当我再次点击它们时,我想让div变回红色。我尝试使用jQuery的animate()方法(使用jQuery颜色插件)更改div的颜色。但是,下面的代码只是部分工作。jQuery animate()不适用于If-Else Statement
$(document).ready(function(){
$("div").click(function() {
$("div").each(function() {
if (this.style.color !== "blue") {
$(this).animate({
color:'blue'
},1000);
} else {
this.style.color = "red";
}
});
});
});
当我点击一个div,如果语句工作正常。 divs变成蓝色。但是,当我再次点击div时,div不会变回红色。 else语句似乎不起作用。对我的错误有任何想法? else语句的工作原理是当我将$(this).animate({...})
替换为this.style.color = "blue";
时,我认为我在animate()方法中做了错误处理。
下面是HTML文件
<!DOCTYPE html>
<html>
<head>
<title> each() test1 </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
body{
background-color: #000000;
color: #ffffff;
}
div {
font-size: 3em;
color: #ff0000;
text-align: center;
cursor:pointer;
font-weight: bolder;
width: 300px;
}
</style>
</head>
<body>
<div> Click here </div>
<div> to iterate through </div>
<div> these divs </div>
</body>
<script src="theJavaScriptFile.js"> </script>
</html>
你尝试$(本)的.css( “颜色”, “红”)? – Vivick
它可能永远不会“蓝色”。请使用[浏览器控制台(开发工具)](https://webmasters.stackexchange.com/q/8525)(点击'F12')并使用'console.log(this.style.color);'调试这个。 – Xufox
如果你在if语句之前使用console.log this.style.color,你会得到什么? – nixkuroi