今日總結:html+js 由前一個下拉框的值的改變從而改變另一個下拉框的值


前言:本文非原創。摘自: 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>根據一個下拉框改變另外一個下拉框的內容</title>
</head>

<body> 
    
<!第一個下拉框內容>
<select id="initials" onchange="Change_second_selectwords();"> 
    
    <option value="">Initial keywords</option> 
    <option value="A">A</option> 
    <option value="B">B</option> 
    <option value="C">C</option> 
</select> 


<select id="top_domains"></select> 
    <script>
        var first_keywords = {};
        //定義每個字母對應的第二個下拉框
        first_keywords['A'] = ['a1', 'a2', 'a3'];
        first_keywords['B'] = ['b1', 'b2', 'b3'];
        first_keywords['C'] = ['c1', 'c2', 'c3'];
        function Change_second_selectwords() {
            //根據id找到兩個下拉框對象
            var target1 = document.getElementById("initials");
            var target2 = document.getElementById("top_domains");
            //得到第一個下拉框的內容
            var selected_initial = target1.options[target1.selectedIndex].value;

            //清空第二個下拉框
            while (target2.options.length) {
                target2.remove(0);
            }
        //根據第一個下拉框的內容找到對應的列表
        var initial_list = first_keywords[selected_initial];
        if (initial_list) {
            for (var i = 0; i < initial_list.length; i++) {
                var item = new Option(initial_list[i], i);
                //將列表中的內容加入到第二個下拉框
                target2.options.add(item);
            }
        }
} 
        </script>
</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM