2017-02-23 5 views
1

私はonChangeの機能を学ぼうとしています。私はこのコードをつかんで自分のサイトに実装していますが、実際にはユーザーが選択した値が表示されますが、クロムの変数にログを記録しようとすると、 Uncaught ReferenceError: x is not definedと表示されます。何故ですか?なぜ私は車を選んだ後でも変数が定義されていません。もう1つの質問。これはjavascriptかJqueryですか?javascript変数として選択したオプションを保存

CODE

<!DOCTYPE html> 
<html> 
<body> 

<p>Select a new car from the list.</p> 

<select id="mySelect" onchange="myFunction()"> 
    <option value="Audi">Audi 
    <option value="BMW">BMW 
    <option value="Mercedes">Mercedes 
    <option value="Volvo">Volvo 
</select> 

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p> 

<p id="demo"></p> 

<script> 
function myFunction() { 
    var x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
</script> 

</body> 
</html> 
+0

あなたのオプションであなたの質問の一部分にはタグはありません: '' –

答えて

2

これはあなたの投稿のJavaScriptです。

あなたがこれを行う場合は、次の

function myFunction() { 
    var x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
    console.log("x:",x); 
} 

xは、関数のスコープ内にあるため、使用可能です。

グローバルスコープのような変数を定義することは、一般に悪い習慣です。この

var x = {}; 
function myFunction() { 
    x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
myfunction();// call it 
console.log("x:",x); 

冗長バージョン:(オブジェクト上の基本的に同じですが、明示的なwindow)は、私が選択した値を取得する方法を追加注意してください。ここhttps://jsfiddle.net/MarkSchultheiss/bqwd784p/

ませんjQueryのだけではJavaScript:ここ

window.x = {}; 

function myFunction() { 
    window.console.log("in here"); 
    var selectElem = document.getElementById("mySelect"); 
    var optsCount = selectElem.options.length; 
    var index = selectElem.selectedIndex; 
    window.console.log("opts", optsCount, index); 
    // return the value of the selected option 
    window.console.log(selectElem.options[selectElem.selectedIndex].value) 
    window.x = selectElem.options[selectElem.selectedIndex].value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
window.myFunction(); // call it 
window.console.log("x:", window.x); 

は、最後の例のフィドルです。

+0

答えを説明していただきありがとうございます。私はたくさん学び、それを働かせました:-) –

2

あなたの変数は関数スコープで宣言され、割り当てられています。あなたが機能

<script> 
var x; 
function myFunction() { 
    x = document.getElementById("mySelect").value; 
    document.getElementById("demo").innerHTML = "You selected: " + x; 
} 
</script> 

の外にそれを宣言する必要があり、関数スコープのそれ利用できる外をしたい場合は、あなたの関数がトリガされるまで、それは未定義になります。これは、DOM APIを使用したプレーンなバニラJSです。

+0

私はそれを試みます。ありがとう。 –

+0

@KakiSamiオプションで、関数内から 'window.x = document.getElementById(" mySelect ")。value';でグローバルに割り当てることができます。 – Bright

+0

ありがとうございました。私は飛行機でそれを宣言することになったし、その後、グローバルになった。 "format = document.getElementById(" format ")。value" –

関連する問題