1

バッチという名前のドロップダウンリストがあります。2番目のオプションを選択した場合、OnChange関数内のdropdown.selectedIndexは常に選択されたインデックスを表示します。ただし、document.getElementById( "batches")。selectedIndexは常に最初のインデックスを表示します。
どうしてこれなの?
実際、別の関数でバッチの正しいselectedIndexを読み取りたいので、両方の方法で正しい選択されたインデックスを取得する方法が必要です。

function OnChange(dropdown){
   var myindex  = dropdown.selectedIndex;// This prints correctly
   alert("Index : "+document.getElementById("batches").selectedIndex);// This is always 0 no metter what selects        
}

<select name='batches' id='batches' onchange='OnChange(this);'>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
4

2 に答える 2

1

関数onChangeイベントを呼び出すため、つまり過去ではありません。onchangeイベントなしで関数をトリガーしてみてください。プロパティは、過去に選択されています。

        <select name='batches' id='batches' onchange='someFunc();'>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
<a href="javascript:someFunc()">Test</a>

<script>
function someFunc(){
   //var myindex  = dropdown.selectedIndex;// This prints correctly
   alert("Index : "+document.getElementById("batches").selectedIndex);// This is always 0 no metter what selects        
}
</script>

それが動作します。このコードをコピーしてテキストエディタに貼り付け、テストするだけです

于 2012-08-08T00:36:47.083 に答える
1

テストしているブラウザはわかりませんが、テストしたすべてのブラウザで常に次のことが当てはまります。

<select id="batches" onchange="
  alert(this.selectedIndex == document.getElementById('batches').selectedIndex);
">
  <option value = "1">1
  <option value = "2">2
  <option value = "3">3
</select>

<!-- and to confirm... -->
<button onclick="
  alert(document.getElementById('batches').selectedIndex);
">Show selected index</button>

オプション値1、2、および3をselectedIndexes 0、1、および2に相関させることで、混乱しないことを願っています。

于 2012-08-08T03:07:12.867 に答える