2016-07-04 2 views
0

Это задано 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> 
+0

Вы можете утешить его в браузере? – binariedMe

+0

Возможный дубликат [Почему метод jQuery или DOM, такой как getElementById, не находит элемент?] (Http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such- as-getelementbyid-not-find-the-element) – Teemu

+0

Разве Visual Studio не жаловалась на не объявленную переменную? – Teemu

ответ

5

Вы недостающие цитаты:

document.getElementById(inputField); 

Должно быть:

document.getElementById('inputField'); 
+0

Это решило, спасибо! Strange Visual Studio не поймал его, но в Js все возможно, я думаю – Plumpie

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 
} 
Смежные вопросы