2016-07-04 57 views
0

這已被問到100x之前,但閱讀了很多這些帖子後,我仍然不知道我做錯了什麼。該腳本僅在按下按鈕時執行(因此,在執行代碼時文本框應該存在於DOM中),Visual Studio甚至允許我自動完成inputField的getElementByID參數。然而不知何故,它沒有得到元素,'null'被打印在我的屏幕上。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或諸如getElementById之類的DOM方法未找到該元素?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such- as-getelementbyid-not-the-element) – Teemu

+0

Visual Studio是否抱怨未聲明的變量? – Teemu

回答

5

你錯過了引號:

document.getElementById(inputField); 

應該是:

document.getElementById('inputField'); 
+0

解決了它,謝謝!奇怪的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 
}