如何从输入表单中获取值,并在我的一个javascript函数中使用它
下面是我的代码,我希望能够使用任何用户输入作为showColor函数的值。我使用document.getElementsByName,但在类型错误时出现了一些错误。有人能帮忙吗?谢谢如何从输入表单中获取值,并在我的一个javascript函数中使用它,javascript,html,Javascript,Html,下面是我的代码,我希望能够使用任何用户输入作为showColor函数的值。我使用document.getElementsByName,但在类型错误时出现了一些错误。有人能帮忙吗?谢谢 <input type="text" name="color" value="Input Your Fav Color"> <button type="button" onClick="showColor('red')">Show Color</button> 显色 我猜是因
<input type="text" name="color" value="Input Your Fav Color">
<button type="button" onClick="showColor('red')">Show Color</button>
显色
我猜是因为你这么做了
document.getElementsByName('color').value
你应该这样做
document.getElementsByName('test')[0].value
因为
getElementsByName
返回一个集合,或者为元素指定一个id
并使用getElementById
您实际上需要使用.getElementById(“color”)并将输入设置为
<input type="text" name="color" id="color" value="Input Your Fav Color">
您需要为目标
输入指定一个id,以便通过javascript轻松检索其值
<input id="userColor" type="text" name="color" value="Input Your Fav Color" >
或者用你的例子
<button type="button" onClick="showColor(document.getElementById('userColor').value)">Show Color</button>
显示颜色
使用DOM:
<button type="button" onClick="showColor(document.getElementsByName('color')[0].value)">Show Color</button>
显示颜色
如果页面上有更多名为color
的元素,就会出现问题,但我认为您没有。那么您的意思是getElementsByName将返回一个同名的值数组?@LoLoLoit实际上是NodeList
,但是的,它是集合。
<button type="button" onClick="showColor(document.getElementsByName('color')[0].value)">Show Color</button>