簡體   English   中英

通過數組時,文本變為未定義

[英]Text becomes undefined when going through an array

現在,我是網絡編程的新手,特別是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;
}

您將增加點擊並單擊2然后應用它。 你應該初始化點擊並點擊2與-1; 點擊初始化為0,名稱[++ click2]將不會先返回第二個項目。

var click = -1;

//Another click var
var click2 = -1;

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

應該

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

您應該確保調用namesimgs可用索引。 在第三個之后,你將撥打4號電話並且沒有定義。

你可以這樣做:

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

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

這將使數字保持在0和2之間。

事情發生這種情況:操作員%a % b將返回時,你休息ab 例如, 5 % 2 == 1

你的最后一個if語句沒有將click2指定為-1。 將其更改為click2 = -1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM