【问题标题】:Text becomes undefined when going through an array遍历数组时文本变得未定义
【发布时间】: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 新手:请注意,明确使用 ArrayObject 构造函数被认为是不好的做法。当您省略 new 关键字时,情况会更糟。所以要么使用(badnew Array();,要么使用常用的(并被接受为更好的选择)var myArray = []; var myObject = {};

标签: javascript arrays string


【解决方案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;
}

【讨论】:

  • 谢谢!像错字这样愚蠢的事情让我伤心了 20 分钟。
【解决方案2】:

您应该确保调用您的namesimgs 的可用索引。在第三个之后,您将拨打号码4,这没有定义。

你可以这样做:

document.getElementById("nam").innerHTML = names[(++click2)%names.length];

document.getElementById("first").src = imgs[(++click)%imgs.length];

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

发生的事情:a % b 中的运算符% 在将a 除以b 时返回余数。例如是5 % 2 == 1

【讨论】:

  • 很好的解决方案。但是解释一下模数的作用。
【解决方案3】:

您的最后一个 if 语句未将 click2 分配给 -1。将其更改为 click2 = -1

【讨论】:

    【解决方案4】:

    你是增加点击和点击2然后应用它。你应该初始化点击 并单击2与-1;由于 click 由 0 初始化,names[++click2] 将返回第二个项目而不是第一个。

    var click = -1;
    
    //Another click var
    var click2 = -1;
    

    还有

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

    应该是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 2012-08-25
      • 2021-10-23
      • 2021-09-06
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多