简体   繁体   English

初学者JavaScript:更改if,else if或else进行切换

[英]Beginner JavaScript: change if, else if, else to switch

Im in an intro JavaScript class and I have a homework assignment where I need to switch a picture every 5 seconds. 我在一个JavaScript入门课程中,我有一个家庭作业,需要每5秒切换一次图片。 I had it written out as a if, else if, else statement and it worked fine but then I saw on the directions that it's supposed to be a switch statement. 我把它写成if,else if,else语句,它工作正常,但是后来我发现它应该是switch语句。 Now I am having a tough time getting it to work. 现在我很难上班了。 If anyone can help me out and let me know what Im doing wrong, that'd help a lot. 如果有人可以帮助我,让我知道我做错了什么,那将大有帮助。

This is what I had: 这就是我所拥有的:

var currAd = "pic1"; 
function changeAd() { 
if (currAd == "pic2") { 
document.images[0].src = "cvb1.gif"; 
currAd = "pic1"; 
} 
else if (currAd == "pic3") { 
document.images[0].src = "cvb2.gif"; 
currAd = "pic2"; 
} 
else { 
document.images[0].src = "cvb3.gif"; 
currAd = "pic3"; 
} 
}

This is the switch statement. 这是switch语句。 I assume its not working because of the currAd variable being the same on all of the cases, but I dont know what to switch it to 由于所有情况下的currAd变量都相同,因此我认为它不起作用,但是我不知道将其切换为什么

var currAd; 
function changeAd() { 
switch (currAd) { 
case currAd: 
return document.images[0].src = "cvb2.gif"; 
case currAd: 
return document.images[0].src = "cvb3.gif"; 
default: 
return document.images[0].src = "cvb1.gif"; 
} 
}

Each case is the value you're comparing currAd with. 每种case都是您要比较currAd的值。 You're currently comparing it to itself, when you should be comparing it to pic2 , pic3 , etc. 您目前是比较它自己,当你要比较它pic2pic3 ,等等。

switch(curaAd) {
case "pic1":
  // ...

Change your switch statement to: 将您的switch语句更改为:

switch (currAd) { 
    case "pic1": 
        return document.images[0].src = "cvb2.gif"; 
    case "pic2": 
    return document.images[0].src = "cvb3.gif"; 
        default: 
    return document.images[0].src = "cvb1.gif"; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM