javascript - js : GetElementByID() doesn't return my element

标签 javascript html

这个问题之前已经被问过 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>

最佳答案

您缺少引号:

document.getElementById(inputField);

应该是:

document.getElementById('inputField');

关于javascript - js : GetElementByID() doesn't return my element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38190299/

相关文章:

javascript - 为什么相同的日期有不同的时间?

javascript - 如何按正则表达式模式拆分并将分隔符保留在长字符串上?

javascript - 在 IF 语句中同时使用 AND 和 OR

php - 使用带空格的 $POST 变量

javascript - 输入标签未正确附加到 div 内。

javascript - document.getElementById ('a' ).click() 在 IE 中不起作用

javascript - 在页面上列出博主帖子,带有图像并使用 CSS 进行风格化

HTML - 滚动时 Safari 中 div 框消失的奇怪问题

c# - div 上方的隐藏按钮

html - 如何为不支持 Shadow DOM 的浏览器创建 CSS 回退?