繁体   English   中英

DropDown List SelectedIndex不能在javascript中使用getElementById

[英]DropDown List SelectedIndex is not working with getElementById in javascript

我有一个名为批处理的DropDown列表。 如果我选择了第二个选项,则OnChange函数中的dropdown.selectedIndex将始终显示所选索引。 但是document.getElementById(“批处理”)。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>

因为你调用函数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>

它会工作。 只需将此代码复制并粘贴到文本编辑器中并进行测试即可

我不知道您正在测试哪种浏览器,但以下内容始终在我测试的所有浏览器中都显示为:

<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相关而感到困惑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM