我有这个 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模板网!