javascript - 遍历数组时文本变得未定义

标签 javascript arrays string

现在,我是网络编程的新手,尤其是 javascript。我正在尝试编写一个脚本,该脚本将在用户单击图像时更新网页上的图像及其文本。这是代码:

//Images array
imgs = Array("test1.jpg", "test2.jpg", "test3.jpg");

//Names array
names = Array("Test1", "Test2", "Test3");

//Holds how many times our page has been clicked
var click = 0;

//Another click var
var click2 = 0;

//change function 
function change()
{

//Get the ID of 'nam', and start incrementing the elements in our array
document.getElementById("nam").innerHTML = names[++click2];

//Get an element with the ID 'first', and start incrementing the elements in  our      array
document.getElementById("first").src = imgs[++click];

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click = -1;
}

}

可能不是执行此操作的最佳方法,但此代码一开始会起作用。但是,当我单击第三张图片返回第一张图片时,图片工作正常,但文本变为“未定义”。我四处搜索,但似乎找不到此代码有任何真正“错误”的地方。

感谢任何帮助。

最佳答案

变量名错别字:

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click = -1;
}

应该是

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click2 = -1;
}

关于javascript - 遍历数组时文本变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13110223/

相关文章:

c - 访问结构体中包含的数组

javascript - 通过与javascript中数组的单词进行比较来连接字符串的单词

javascript - JQuery - 检查 IMG src 是否有效

java - 将 WAV 文件复制到剪贴板

Java:设置预定长度的数组作为方法参数?

python - 为什么Python既有格式函数又有格式方法

string - Swift String 编码和 NSXMLParser 解析问题

javascript - Angular 2 中的条件验证

php - 那里有锦标赛 API 吗?

python - 在 Python 中拆分数组