JQuery beginner here。私はそれらをクリックすると、一組のdivが赤から青に変わるようにしようとしています。もう一度クリックすると、divが赤に戻ってきます。私はdivの色を変更するjQueryのanimate()メソッド(jQueryカラープラグイン)を使用してみました。しかし、以下のコードは部分的にしか動作しません。jQuery animate()はIf-Elseステートメントでは機能しません。
$(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).animate({...})
をthis.style.color = "blue";
に置き換えたときにelseステートメントが動作するので、私はanimate()メソッドで何か問題があると思っています。ここで
blue
または
red
カラーコードを使用していない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
おそらく ''青い ''でしょう。これをデバッグするには、[browser console(dev tools)](https://webmasters.stackexchange.com/q/8525)( 'F12'を押す)と' console.log(this.style.color); 'を使用してください。 – Xufox
if文の直前でconsole.log this.style.colorの場合はどうしますか? – nixkuroi