首页 > 选中select 里面的某个option时如何触发事件?

选中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>

jQuery

$("#mySelect").change(function(){ 
    alert($(this).val());
});

<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>
【热门文章】
【热门文章】