設定下拉框中的選中項
阿新 • • 發佈:2018-11-06
點選設定按鈕下拉框隨機選中
<!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>