嗯,我花了很长时间摆弄这个,但进展甚微。我已经看到了很多解决方案,但是将它们应用到我的情况中却不起作用,我真的不知道为什么。
我试图让一些图像在单击时更改下拉菜单的选定值,从而导致下拉菜单上发生 onchange 事件。
<script type="text/javascript">
function parse_theme(input){
var index = document.getElementById('themes').length; /* this bit is working fine */
for(var i=0;i<=index;i++;){
if(document.getElementById('themes').options[i].value == input){ /*error is here */
document.getElementById('themes').selectedIndex = i;
}
}
}
</script>
和 html:
<select id="themes" style="display:none;" onchange="selectTheme()">
<option value="default" selected="selected">default</option>
<option value="ambiance">ambiance</option>
<option value="cobalt">cobalt</option>
</select>
<img id="default" onclick="parse_theme(this.id)" src="images/default.png" width="10" height="10">
<img id="ambiance" onclick="parse_theme(this.id)" src="images/ambiance.png" width="10" height="10">
<img id="cobalt" onclick="parse_theme(this.id)" src="images/cobalt.png" width="10" height="10">
我收到“未捕获的类型错误:无法读取未定义的属性“值”。
onchange 函数工作正常,但是当我只有下拉菜单时,我希望它通过一系列图像来完成,并让图像引用列表中的选项并使列表不可见。
最佳答案
更改为
for(var i=0;i<index;i++;){
循环的最后一个索引可能会失败,因为索引值为 3,您将循环 0,1,2,3 而不是仅 3 次
关于javascript - 更改下拉菜单中选定的选项,从而引发 onchange 事件; javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14942307/