javascript - 选中select 里面的某个option时如何触发事件?

查看:117
本文介绍了javascript - 选中select 里面的某个option时如何触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如下代码,当我点击按钮时,可以得到option里面弹出value的值,我想问的是如何不点击按钮,直接给option绑定事件,当选中某个option时触发事件,弹出option的value值?

<html>
<head>
<script type="text/javascript">
function getIndex()
  {
  var x=document.getElementById("mySelect")
  alert(x.options[x.selectedIndex].value);
  }
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option value="20">Apple</option>
  <option value="30">Orange</option>
  <option value="40">Pineapple</option>
  <option value="50">Banana</option>
</select>
<br /><br />
<input type="button" onclick="getIndex()"
value="Alert index of selected option">
</form>

</body>
</html>

解决方案

<html>
<head>
<script type="text/javascript">
    window.onload = function() {
        var sel = document.getElementById("mySelect");
        if(sel&&sel.addEventListener){
            sel.addEventListener('change',function(e){
                var ev = e||window.event;
                var target = ev.target||ev.srcElement;
                alert(target.value);
            },false)
        }
    }
</script>
</head>
<body>

<form>
Select your favorite fruit:
<select id="mySelect">
  <option value="20">Apple</option>
  <option value="30">Orange</option>
  <option value="40">Pineapple</option>
  <option value="50">Banana</option>
</select>
<br /><br />
<input type="button" value="Alert index of selected option">
</form>

</body>
</html>

这篇关于javascript - 选中select 里面的某个option时如何触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆