美文网首页
随机选中下拉框

随机选中下拉框

作者: 王远清orz | 来源:发表于2019-10-09 10:43 被阅读0次
    <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>
    

    相关文章

      网友评论

          本文标题:随机选中下拉框

          本文链接:https://www.haomeiwen.com/subject/tovwpctx.html