<select>標籤的簡單用法
阿新 • • 發佈:2020-07-19
HTML:
<!DOCTYPE html> <html> <body> <div> <div> <label>請選擇:</label> </div> <div> <select id="add_number"> <option id="on">是</option> <option id="off">否</option> </select> </div> </div> </body> <script type="text/javascript"> </script> </html>
顯示:
切換事件:
document.getElementById("add_number").onchange = function(){
alert("add_number發生切換")
}
遍歷選項:
var options = document.getElementById("add_number").options
for (i=0; i<options.length; i++){
alert(options[i].innerHTML)
}
判斷被選中選項:
var options = document.getElementById("add_number").options for (i=0; i<options.length; i++){ if(options[i].selected == true){ alert("被選中選項:" + options[i].innerHTML) } }
完整例子:
<!DOCTYPE html> <html> <body> <div> <div> <label>請選擇:</label> </div> <div> <select id="add_number"> <option id="on">是</option> <option id="off">否</option> </select> </div> </div> <button id="btn1">列印所以選項</button> <button id="btn2">判斷當前選項</button> </body> <script type="text/javascript"> document.getElementById("add_number").onchange = function(){ alert("add_number發生切換") } document.getElementById("btn1").onclick = function(){ var options = document.getElementById("add_number").options for (i=0; i<options.length; i++){ alert(options[i].innerHTML) } } document.getElementById("btn2").onclick = function(){ var options = document.getElementById("add_number").options for (i=0; i<options.length; i++){ if(options[i].selected == true){ alert("被選中選項:" + options[i].innerHTML) } } } </script> </html>