2012-10-19 36 views
1

我有我的第10頁的輸入框變..獲取的getElementById從使用JavaScript

<input type="text" id="box1"> 
<input type="text" id="box2"> 
<input type="text" id="box3"> 
<input type="text" id="box4"> 
<input type="text" id="box5"> 
<input type="text" id="box6"> 
<input type="text" id="box7"> 
<input type="text" id="box8"> 
<input type="text" id="box9"> 
<input type="text" id="box10"> 

使用JavaScript我希望能夠選擇每個輸入,但僅應要求使用JavaScript。

我用下面的代碼:

document.getElementById("box1").value 

其返回值(我想)

但是我希望能夠做一些事情有那麼請求,那麼下一個項目做一些事情與..

所以我創建了一個虛擬變量(把我的功能之外,因爲我不希望值回每個函數被調用時重置爲1:

var current_item = "1"; 

然後我希望能夠選擇使用此變量的項目,我已經用它喜歡:

document.getElementById("box" + current_item).value 
current_item = current_item + 1; 

但它不工作。 如果我警告current_item變量,它將返回undefined。

如果我的current_item變量添加到我的功能,它的工作原理和做什麼,我想要它做的,而是不斷重新回到1(作爲功能重建的變量)。

誰能幫我出這個關於如何獲得下一個輸入框的值?

+0

是它的工作的第一次?當推測current_item是一個?我在想第二次你在找「box11」和第三次「box111」 – Sap

+0

第一次沒有工作..當我運行它時,它回來說undefined。當我添加var current_item =「1」;到它的工作功能,但從來沒有增加數字,它始終設置爲1. – Aaron

回答

2

試着做current_item一些,而不是字符串。

var current_item = 1; 

代替

var current_item = "1"; 

jsFiddle example

+0

當我運行我的腳本時,它工作正常,當我添加var current_item = 1;到相同的功能,但如果我添加var current_item = 1;在我的函數外面它返回undefined。 – Aaron

+0

你可以創建一個顯示這個問題的jsFiddle嗎? – j08691

+0

我必須有另一個問題,一旦我將它加載到jsFiddle它的工作..所以我的網頁上必須有一個錯誤的地方。 – Aaron

2

current_item是一個字符串,當您使用+運營商,它代替實施串聯。

"1" + 1 
"11" 

如果使用var current_item = 1;,這將是一個整數,你可以通過做+1

另外補充它,

var current_item = "1"; 
current_item = current_item*1 + 1; 
2 

當你乘1時,它轉換成int,然後加1,結果如你所期望的那樣2。

相關問題:Javascript (+) sign concatenates instead of giving sum of variables

+0

如果'current_item'是一個數字,那麼也可以執行'++ current_item'和'current_item + = 1' – RobG

1

我的猜測是,你與不同類型搞亂。 current_item開始爲一個字符串,並且添加了一些這樣的current_item + 1結果將是112。嘗試與:

var current_item = 1 
相關問題