如果java脚本中的条件为true,则statement始终为false

时间:2017-05-16 08:43:45

标签: javascript

这是javascript和HTML和CSS我是javascript的新手问题是if语句总是显示错误,即使它不应该if语句总是为false,即使我点击win变量的颜色值数组的第3个索引的值显示错误

var colors = [
	"rgb(255,0,0)",
	"rgb(255,255,0)",
	"rgb(0,255,0)",
	"rgb(0,255,255)",
	"rgb(0,0,255)",
	"rgb(255,0,255)"
	]
var win =colors[3];
var winclrdisplay=document.querySelector(".winclr");
var square= document.querySelectorAll(".square");

	winclrdisplay.textContent=" "+ win;
	
	for (var  i = 0 ;i < square.length ; i++){
		//colors 
		square[i].style.background =colors[i];
		
		// click listener
		square[i].addEventListener("click", function(){
		 var click = this.style.background;
		 if (click == win){
		 	alert("correct");
		 }else{
		 	alert("wrong");
		 }
		}
 		);
	} 
body {
	background-color: #232323;
}

.square{
	width: 30%;
	background: purple;
	padding-bottom: 30%;
	float: left;
	margin: 1.66%;


}

#container {
	max-width: 600px;
	margin: 0 auto;
}
h1 {
	color:white;
}
<html>
<head>
	<title>color guessing game</title>
	<link rel="stylesheet" type="text/css" href="colorapp.css">

</head>
<body>
	<h1>The Great <span class="winclr"></span> colour Game</h1>
	
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="colorapp.js"></script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

使用element.getComputedStyle。如果css样式是内联的,element.style将获取值。它总是假的,因为它没有价值。

类似这样的事情

var element = document.getElementById('box'),
            style = window.getComputedStyle(element),
            bg = style.getPropertyValue('background-color');

    console.log(bg);

答案 1 :(得分:0)

几乎不可能理解你的问题,因为格式不正确。但是,通过快速查看,您错过了)声明中的结束if

if (click == "rgb(0,255,255"){

应该是

if (click == "rgb(0,255,255)"){

if (click == rgb(0,255,255)){

(再一次,我不确定你的目标是什么)