选中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>
阅读 30.2k
2 个回答
<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>

jQuery

$("#mySelect").change(function(){ 
    alert($(this).val());
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏