设置下拉框中的选中项

点击设置按钮下拉框随机选中

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>设置下拉框中的选中项</title>
</head>

<body>
    <select id="selCities">
        <option value="1">南京</option>
        <option value="2">上海</option>
        <option value="3">广州</option>
        <option value="4">杭州</option>
    </select>
    <input type="button" value="设置" id="btnSet">
    <script>
        //1.给按钮注册事件
        var btnSet = document.getElementById("btnSet");
        btnSet.onclick = function() {
            //2.获取下拉框中的所有option
            var selCities = document.getElementById("selCities");
            var options = selCities.getElementsByTagName("option");
            //3.随机生成索引
            //Math.random()->[0,1)
            //Math.random()*4->[0,4)
            var randomIndex = parseInt(Math.random() * options.length);
            //4.根据索引获取option,并让option选中
            var option = options[randomIndex];
            option.selected = true;
        }
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_42442123/article/details/83616229