JavaScript:如何使if语句做两件事

时间:2017-04-30 15:39:50

标签: javascript

以下是一段代码的摘录:

if (lightColour === fileArray[0]) {
   lightColour = "RedOrangeLight.jpg";
   lightTimer = "5000";
}

假设lightColour确实等于fileArray[0],我该如何处理我的代码,以便lightColour等于"RedOrangeLight.jpg"lightTimer也会分配值"5000"

- 编辑 -

好的,非常清楚,这不是非常有用或有帮助的。我将在下面发布完整的代码:

<!DOCTYPE html>
<html>
<body>

<h1>Changing Traffic Lights w/ Arrays</h1>

<img id="trafficLight" src="RedLight.jpg">

<script>

var lightTimer = "1000"
var lightColour = trafficLight.src

var fileArray = ["RedLight.jpg",
                 "RedOrangeLight.jpg",
                 "GreenLight.jpg",
                 "OrangeLight.jpg"];

function lightChange() {

if (lightColour === fileArray[0]) {
   lightColour = "RedOrangeLight.jpg";
   lightTimer = 5000;
} else if (lightColour === fileArray[1]) {
   lightColour = "GreenLight.jpg";
   lightTimer = 1000;
} else if (lightColour === fileArray[2]) {
   lightColour = "OrangeLight.jpg";
   lightTimer = 5000;
} else {
  lightColour = "RedLight.jpg";
  lightTimer = 1000;
}

var light = document.getElementById('trafficLight');
light.src = lightColour

}

setInterval(lightChange, lightTimer);

</script>

</body>
</html>

关于我做错了什么的任何迹象?

2 个答案:

答案 0 :(得分:0)

您仅在功能之外定义了setInterval 超时一次。这就是为什么它不会使用新的 if / else 值进行更新的原因!

<强>解决方案: 使用您的函数内的setTimeout 来更新超时值:

&#13;
&#13;
var light = document.getElementById('trafficLight'); // Place it here!!
var lightTimer = 1000;
var lightColour = trafficLight.src;
var fileArray = [
  "//placehold.it/50x50/f00", // red
  "//placehold.it/50x50/f40", // redorange
  "//placehold.it/50x50/3f0", // green
  "//placehold.it/50x50/f80"  // orange
];

function lightChange() {

  if (lightColour === fileArray[0]) {
    lightColour = "//placehold.it/50x50/f40"; // redorange
    lightTimer = 1000;
  } else if (lightColour === fileArray[1]) {
    lightColour = "//placehold.it/50x50/3f0"; // green
    lightTimer = 5000;
  } else if (lightColour === fileArray[2]) {
    lightColour = "//placehold.it/50x50/f80"; // orange
    lightTimer = 1000;
  } else {
    lightColour = "//placehold.it/50x50/f00"; // red
    lightTimer = 5000;
  }

  light.src = lightColour

  // use setTimeout here instead
  setTimeout(lightChange, lightTimer);

}

lightChange(); // Start!!
&#13;
<h1>Changing Traffic Lights w/ Arrays</h1>

<img id="trafficLight" src="//placehold.it/50x50/f00">
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

如果您想要5000的值,请删除它周围的引号。如果将变量设置为"5000",则变量将是字符串而不是数字。删除引号将使其成为一个数字。

代码应如下所示

lightTimer = 5000;

相对应

lightTimer = "5000";