Это задано 100 раз раньше, но после прочтения многих этих сообщений я все еще не уверен, что я делаю неправильно. Сценарий выполняется только при нажатии кнопки (поэтому текстовое поле должно существовать в DOM к моменту выполнения кода), Visual Studio даже позволяет мне автозаполнять аргумент getElementByID для inputField. Но каким-то образом он не получает элемент, а на моем экране напечатан «нуль».Js: GetElementByID() не возвращает мой элемент
Мой код:
<!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>
Вы можете утешить его в браузере? – binariedMe
Возможный дубликат [Почему метод jQuery или DOM, такой как getElementById, не находит элемент?] (Http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such- as-getelementbyid-not-find-the-element) – Teemu
Разве Visual Studio не жаловалась на не объявленную переменную? – Teemu