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