随机选中下拉框

2019-10-09  本文已影响0人  王远清orz
<body>
  <input type="button" value="设置" id="btnSet">
  <select name="" id="selCities">
    <option value="1">广州</option>
    <option value="2">上海</option>
    <option value="3">深圳</option>
    <option value="4">北京</option>
    <option value="5">武汉</option>
  </select>
  <script>
  // 1.给按钮注册点击事件
  var btnSet = document.getElementById('btnSet');
  btnSet.onclick = function () {
    // 2.获取select中的option元素
    var selCities = document.getElementById('selCities');
    var options = selCities.getElementsByTagName('option');
    console.log(options);
    // 3.随机生成索引   option索引应该在0-options.length之间
    var optionIndex = parseInt( Math.random() * options.length); //Math.random()返回 [0,1)
    console.log(optionIndex);
    // 4.根据索引选中option,并让其选中
    var option = options[optionIndex];
    console.log(option);
    option.selected = true;
  }
  
  </script>
</body>
上一篇下一篇

猜你喜欢

热点阅读