JavaScript getElementByName不起作用

这个简单的JS不能设置“ para”的值。我猜getElementByName不起作用。但为什么?


<script>

function fn()  

{   

    document.getElementById("para").setAttribute("name","hi");  

    document.getElementByName("hi").setAttribute("value","my value is high");  

}  

</script>

HTML:


<input type="button" onClick="fn()" value="click me">

<input id="para" type="text" />


回首忆惘然
浏览 583回答 3
3回答

慕森王

是getElementsByName。注意复数。它返回具有该name属性的元素的类似数组的NodeList&nbsp;。

一只萌萌小番薯

getElementsByName存在,它返回元素的集合。如果您只打算找到一个:document.getElementsByName("hi")[0].setAttribute("value", "my value is high");编辑:a,有HTML(在编辑之前没有看到)。HTML中没有'hi'元素,可能是某些XML格式...

慕尼黑8549860

不getElementByName但是getElementsByName,它返回数组。<html><head>&nbsp; &nbsp; <script language="javascript">&nbsp; &nbsp; &nbsp; &nbsp; function fn() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("para").setAttribute("name","hi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x = document.getElementsByName("hi");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x[0].setAttribute("value","my value is high");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></head><body onload="fn()">&nbsp; &nbsp; <input type="text" id="para" /></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript