输入类未定义,但输入ID有效

时间:2014-12-12 18:28:47

标签: javascript html dom

当我将以下项目<input type="text" id="myText"更改为<input type="text" class="myText"document.getElementById("myText")更改为document.getElementsByClassName("myText")

时,不确定为什么结果未定义

http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_text_value

2 个答案:

答案 0 :(得分:0)

getElementsByClassName()返回一个nodeList,所以如果你想让你的例子工作,你必须像这样使用它:

<!DOCTYPE html>
<html>
    <body>
        First Name: <input type="text" class="myText" value="Mickey">
        <p>Click the button to display the value of the value attribute of the text field.</p>
        <button onclick="myFunction()">Try it</button>
        <p id="demo"></p>
    <script>
        function myFunction() {
           var x = document.getElementsByClassName("myText");
           document.getElementById("demo").innerHTML = x[0].value;
        }
    </script>

    </body>
</html>

答案 1 :(得分:0)

您提到了一个带有示例的链接

document.getElementsByClassName("myText").value;

您不应该这样做,因为getElememtaByClassName函数将返回一组值,而不是像getElementById这样的单个值。

使用数组索引

获取值

查看此documentation