这已被问过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>
答案 0 :(得分:5)
您错过了引号:
document.getElementById(inputField);
应该是:
document.getElementById('inputField');
答案 1 :(得分:0)
根据@Schlaus的回答,我创建了一个jsfiddle并给出了正确答案。
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
}