Javascript jQuery animate()不适用于If-Else语句

Javascript jQuery animate()不适用于If-Else语句,javascript,jquery,Javascript,Jquery,这里是JQuery初学者。我试图让一组div在我点击时从红色变为蓝色。当我再次单击它们时,我希望div变回红色。我尝试在jQuery颜色插件中使用jQuery的动画方法来更改div的颜色。但是,下面的代码仅部分起作用 $(document).ready(function(){ $("div").click(function() { $("div").each(function() { if (this.style.color !== "blue"

这里是JQuery初学者。我试图让一组div在我点击时从红色变为蓝色。当我再次单击它们时,我希望div变回红色。我尝试在jQuery颜色插件中使用jQuery的动画方法来更改div的颜色。但是,下面的代码仅部分起作用

$(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时,if语句工作正常。div变为蓝色。但是,当我再次单击div时,div不会变回红色。else语句似乎不起作用。对我的错误有什么看法吗?当我用this.style.color=blue替换$this.animate{…}时,else语句起作用;所以我觉得我在用动画的方法做错事

这是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> 
只是不要使用蓝色或红色代码。它将被转换为RGB代码。 例如,this.style.color将是RGB0,0255,而不是蓝色,因此无论是什么颜色,表达式始终返回true

我以不同的颜色模式创建了这个示例,供您查看


无论如何,如果你想对特定的颜色有特殊的逻辑,那么就继续使用这种方法。否则,请使用类名而不是颜色代码来确定。因为浏览器总是返回颜色属性的rgb值,所以我会通过使用活动类来控制状态来管理它

如果那样的话,我会成功的改变

$document.readyfunction{ $div.clickfunction{ $.each$this.parent.childrendiv,函数{ 如果!$this.hasClass'active'{ $this.addClass'active'; $this.animate{ 颜色:'蓝色' },1000; }否则{ $this.removeClass'active'; this.style.color=红色; } }; }; }; 每个测试1 身体{ 背景色:000000; 颜色:ffffff; } div.active{} div{ 字号:1em; 颜色:ff0000; 文本对齐:居中; 光标:指针; 字体大小:粗体; 宽度:300px; } 点击这里 反复 这些div 点击这里 反复 这些div
你有没有试过这个。csscolor,红色?它可能永远不会是蓝色的。请使用hit F12并使用console.logthis.style.color;若要调试此命令,请在if语句之前使用console.log this.style.color,结果如何?@nixkuroi nothing,console.log工作正常,但返回为空。@AlexFidelChen在单击时两次都是空的?我尝试了您的示例。当我单击一个div时,div变为蓝色,但在再次单击时不会变回红色。对不起,我无法保存它。在这里试试@HungCao你的例子很有用谢谢。我确实注意到,当我去掉逗号之间的空格时,您的示例停止工作,这意味着我将rgb0,0,255更改为rgb0,0255。知道为什么吗?因为你在比较两个字符串。所以它需要精确匹配。如果要在比较之前删除所有空格,请使用regex this.style.color.replace/\s+/g,==='rgb0,0255',这样我的If语句的条件不能是this.style.color!==0000ff,因为浏览器读取的0000ff与rgb0、0、255不一样?因为字符串不完全相同?