2011-12-20 13 views

回答

1

我猜那是因爲你這樣做

document.getElementsByName('color').value 

你應該這樣做,而不是

document.getElementsByName('test')[0].value 

因爲getElementsByName返回一個集合,或者給一個元素代替id並使用getElementById

0

實際上,你需要使用.getElementById(「顏色」),並有輸入是

<input type="text" name="color" id="color" value="Input Your Fav Color"> 
1

您將要分配一個id,目標input,這樣你可以很容易地通過JavaScript檢索其值。

<input id="userColor" type="text" name="color" value="Input Your Fav Color" > 

然後你可以檢索像這樣的值:

var usercolor = document.getElementById('userColor').value; 

或使用例如

<button type="button" onClick="showColor(document.getElementById('userColor').value)">Show Color</button> 
+0

這個作品完美!謝謝! – sammiwei

+1

不客氣。快樂的編碼! – mrtsherman

1

使用DOM:

<button type="button" onClick="showColor(document.getElementsByName('color')[0].value)">Show Color</button> 

會有,如果你是問題有更多元素名稱爲color在頁面上,但我假設你沒有。

+0

所以你的意思是getElementsByName會返回一個同名數組的數組?@Lolo – sammiwei

+0

它實際上是'NodeList',但是,它是集合。 – Krzysztof

+0

好的,我明白了!謝謝! – sammiwei

相關問題