問題描述
我有這個 html 代碼:
I have this html code:
<table border="" cellpadding="3" cellspacing="0" id="mytable">
<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
如何獲得歌曲"和藝術家"的值?我試過了:
How do I get the values of "song" and "artist"? I have tried:
var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
但即使文本框中有文本,我也會不斷收到未定義"
but I keep getting "undefined" even when there is text inside the textbox
推薦答案
首先,td
元素沒有value
屬性,所以調用.value
他們不會做任何事情.其次,該值實際上在 input
元素上,因此您需要改為 mytable.getElementsByTagName('input')
.更好的是給你的輸入字段ID,然后使用getElementById
.這意味著您可以在不破壞 JS 的情況下更改 HTML.
First, td
elements don't have a value
attribute, so calling .value
on them won't do a thing. Second, the value is actually on the input
element, so you need to do mytable.getElementsByTagName('input')
instead. Even better would be to give your input fields ids and then use getElementById
. This would mean you could alter your HTML without your JS breaking.
這篇關于在 Javascript 中獲取文本框的值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!