简体   繁体   English

Javascript document.getElementByID(…)为NULL

[英]Javascript document.getElementByID(…) is NULL

i got a problem in Javascript. 我在Javascript中遇到问题。 i want to set a value from text input to a specific value, when clicking a link. 我想点击一个链接时,从文本输入的值设置为特定值。

<form method="get" action="db.php">
<dl>
    <dt>
        Part:
    </dt>
    <dd>
        <input type="text" name="part"></input>
    </dd>
....
....  
<a href="#" onClick="document.getElementById('part').value = 'motor';">motor</a>   

but the 但是

TypeError: document.getElementById(...) is null    

error appear 错误出现

whats wrong with it? 它出什么问题了?

getElementById find an element by id . getElementById通过id查找元素。 There is no elementi with id = part in your dom sample. 您的dom样本中没有id = part elementi。 That's why it returns null. 这就是为什么它返回null的原因。 You could use document.getElementsByName(string) and it would return the array with the elemtns with the name specified, in your could, the 0 index get the input tag! 您可以使用document.getElementsByName(string) ,它将返回带有指定名称的elemtns的数组,您可以使用0索引获取input标签!

<a href="#" onClick="document.getElementsByName('part')[0].value = 'motor';">motor</a> 

It will return and array , so get the first element. 它将返回和array ,因此获取第一个元素。 Would be nice if you check it on a function if you get some result and apply the value property. 如果您在函数上检查它,如果得到一些结果并应用value属性,那将是很好的。

只需将id添加到输入标签,然后就可以使用getElementById('part')

<input type="text" name="part" id="part"></input>

Your <a> has a NAME of "part", not an ID. 您的<a>的名称为“ part”,而不是ID。 Therefor, there is no element on the page with an ID of "part", which is why you get a null result. 因此,页面上没有ID为“ part”的元素,这就是为什么您得到空结果的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM