2017-09-27 1 views
0

私はかなり単純な機能の仕事をするのに苦労していましたが、実際には働きかけていないので、二番目の意見が本当に必要です...私が警戒を覚えようとしています特定のオプションが選択されたときにいつでも上のいずれかを選択すると、何も起こりません。私は何をしているのか分かりません。ここで私が作業しているコードです!jQuery関数は、特定のselectオプション値がアクティブなときに何かを発生させますか?

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> 

<script type="text/javascript"> 

$('#contactType').change(function(){ 
    if($(this).val() === 'complaints'){ 
    alert('you have selected complaints'); 
    } 
    else if ($(this).val() === 'technical') { 
    alert('you have selected technical problems'); 
    } 
    else if ($(this).val() === 'product') { 
    alert('you have selected technical product issues'); 
    } 
}); 

</script> 

<p> 
    <label>Please Select your reason for contactin us. 
    <select name="contactType" id="contactType"> 
     <option value="complaints">Complaints</option> 
     <option value="technical">Technical Problems</option> 
     <option value="product">Product Issues</option> 
    </select> 
    </label> 
</p> 

それだけで動作するようには思えないし、私はそれがダム間違いだ願っていますが、私は正直、この時点で困惑、すべてのものを試してみました。どんな助けもありがとう!

+0

あなたのjsコードは、HTMLがロードされる前に処理されます。したがって、idが 'contactType'のタグがないので、バインドされた変更イベントリスナー –

+0

がないので、$(document).ready関数に入れます???またはスクリプトをフッターに置くだけですか? –

+0

フッターに置きます。https://jsfiddle.net/e65c11wu/ – nodws

答えて

0

スクリプトタグをHTMLの下に移動します。

あなたの参照しようとしている値がまだ存在しないように、javascriptがHTMLレンダリングの前に実行されているため、アラートは機能しません。

スクリプトを下に移動すると、htmlの下に移動すると機能します。

0

問題はタイミングの問題です。 javascriptコードはhtmlがロードされる前に実行されます(htmlマークアップの上に配置され、ロードハンドラ内でラップされないため)。 1)HTMLマークアップ下JSコードを配置:

<script>window.onload =()=>{var foo = document.querySelector('#bar').length;}</script> // foo is 1 
<div id="bar"></div> 

またはjQueryを使って:

<script>$(()=>{var foo = document.querySelector('#bar').length;})</script> // foo is 1 
<div id="bar"></div> 

<script>var foo = document.querySelector('#bar').length;</script> // foo is 0 
<div id="bar"></div> 

<div id="bar"></div> 
<script>var foo = document.querySelector('#bar').length;</script> // foo is 1 

2)ondomreadyイベントを使用

は2つの方法があります

関連する問題