2016-07-04 1 views
0

これは前に100回質問されましたが、これらの投稿を多く読んだ後も、私は何が間違っているのかまだ分かりません。スクリプトは、ボタンを押すと実行されます(コードが実行されるまでにテキストボックスがDOM内に存在する必要があります)。Visual Studioでは、getElementByID引数をinputFieldにオートコンプリートすることもできます。それでも何とか要素を取得せず、画面に「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-find-the-element) – Teemu

+0

Visual Studioは宣言されていない変数について文句を言いませんでしたか? – Teemu

答えて

5

あなたは引用符が欠落している:

document.getElementById(inputField); 

は次のようになります。@Schlaus回答に基づいて

document.getElementById('inputField'); 
+0

それを解決しました、ありがとう! Strange Visual Studioはそれをキャッチしませんでしたが、Jsではすべてが可能です – Plumpie

0

、私は正しいと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 
} 
関連する問題