Js:GetElementByID()不返回我的元素

Plu*_*pie 0 html javascript

这已被问过100次,但在阅读了很多这些帖子后,我仍然不确定我做错了什么.该脚本仅在您按下按钮时执行(因此在执行代码时文本框应存在于DOM中),Visual Studio甚至允许我自动完成inputField的getElementByID参数.但不知怎的,它没有得到元素,我的屏幕上印有'null'.

我的代码是:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <!-- input field + button, and an empty value field --> 
    <input type="text" id="inputField" value="" />
    <input type="button" onclick="printType()" />

</body>


<script>

    function printType() {
        console.log(document.getElementById(inputField).value); //first try to get the value the regular way
        console.log(
            get_type(
            document.getElementById(inputField)
            )
            ); //also try get_type to see if it exists, we're expecting a string
    }



    //stole this function from a stackoverflow post
    function get_type(thing) {
        if (thing === null) return "[object Null]"; // special case
        return Object.prototype.toString.call(thing);
    }



</script>

</html>
Run Code Online (Sandbox Code Playgroud)

Sch*_*aus 5

你缺少引号:

document.getElementById(inputField);
Run Code Online (Sandbox Code Playgroud)

应该:

document.getElementById('inputField');
Run Code Online (Sandbox Code Playgroud)