【发布时间】:2012-10-28 15:39:08
【问题描述】:
现在,我是网络编程的新手,尤其是 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;
}
}
可能不是最好的方法,但这段代码一开始就可以工作。但是,当我单击第三张图片返回第一张图片时,图片工作正常,但文本变为“未定义”。我四处搜索,但我似乎找不到任何与此代码真正“错误”的地方。
感谢任何帮助。
【问题讨论】:
-
使用
[..]创建一个数组。不是Array(..)。实际上在您的示例中应该是new Array(..)。 -
看到您是 Js 新手:请注意,明确使用
Array和Object构造函数被认为是不好的做法。当您省略new关键字时,情况会更糟。所以要么使用(bad)new Array();,要么使用常用的(并被接受为更好的选择)var myArray = []; var myObject = {};
标签: javascript arrays string