search

Home  >  Q&A  >  body text

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>
PHP中文网PHP中文网2820 days ago227

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-10 17:17:02

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 17:17:02

    jQuery

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

    reply
    0
  • Cancelreply