JavaScript - 如何在If / Else语句中提取字符串 [英] JavaScript - How do I extract string in If/Else statement

查看:280
本文介绍了JavaScript - 如何在If / Else语句中提取字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用If / Else语句在搜索imgNumber变量后在屏幕上写入某些文本。出于某种原因,无论imgNumber变量中包含哪个文本,它都只会写出字符串'cockroaches'。

I'm trying to use the If/Else statement to write certain text on the screen after searching through the imgNumber variable. For some reason, it only writes the string 'cockroaches' no matter which text is contained in the imgNumber variable.

此外,imgNumber是一个随机字符串(它始终是myImages变量中的一个字符串)。

Also, the imgNumber is a random string (it will always be one of the strings in the myImages variable).

我在这里缺少什么?

<script type="text/javascript">

function changeImg(imgNumber) {
var myImages = ["images/homepage/homepage-header.jpg", "images/homepage/homepage-header-3.jpg", "images/homepage/homepage-header-5.jpg"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';

var imgNumber = myImages[newImgNumber];

if (imgNumber = "images/homepage/homepage-header-5.jpg")
  {
  document.write('cockroaches');
  }
else if (imgNumber = "images/homepage/homepage-header-3.jpg")
  {
  document.write('ants');
  }
else
  {
  document.write('termites');
  } 

var n=myImages.indexOf("images/homepage/homepage-header-5.jpg");
document.write(n);

}
window.onload=changeImg;
</script>


推荐答案

您的 if 条件错误,需要使用2个等号进行比较。所以: == 不是 =
你在做的是分配字符串的值到您的 imgNumber 变量......

Your if conditions are wrong, you need to compare using 2 equals signs. So: == not = What you're doing in there is assigning the value of the strings to your imgNumber variable...

您可以在 MDN

这篇关于JavaScript - 如何在If / Else语句中提取字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆