Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过数组时,文本将变得未定义_Javascript_Arrays_String - Fatal编程技术网

Javascript 通过数组时,文本将变得未定义

Javascript 通过数组时,文本将变得未定义,javascript,arrays,string,Javascript,Arrays,String,现在,我对web编程,特别是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

现在,我对web编程,特别是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;
}
if(click2==2)
{
    click2 = -1;
}

您可以依次递增单击和单击2,然后应用它。您应该初始化单击 然后用-1单击2;由于单击由0初始化,名称[++click2]将返回第二项而不是第一项

var click = -1;

//Another click var
var click2 = -1;

应该是

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

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

您应该确保调用
名称
imgs
的可用索引。在第三个之后,您将拨打电话号码
4
,但此号码未定义

你可以这样做:

document.getElementById(“nam”).innerHTML=names[(++click2)%names.length]

document.getElementById(“first”).src=imgs[(++click)%imgs.length]

这将使数字保持在0和2之间


发生的情况:当将
a
除以
b
时,
a
中的运算符
%
将返回其余的值。例如,
5%2==1
您的最后一条if语句没有将click2赋值给-1。将其更改为click2=-1

使用
[…]
创建一个数组。不使用
数组(..)
。实际上,在您的示例中应该是
new Array(..)
。鉴于您是Js新手:请注意,显式使用
Array
Object
构造函数被认为是不好的做法。如果省略
new
关键字,情况会更糟。因此,要么使用(坏)
newarray()
或普遍使用的(并被接受为更好的选择)
var myArray=[];var myObject={}好的解决方案。但是解释一下模数的作用。谢谢!像打字错误这样愚蠢的事情让我伤心了二十分钟。