天天看點

Jquery 結合Json控制Select下拉框

Code
<html>
<head>
<title>jquery 操作 Select</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

<script type="text/javascript">
$(document).ready(function(){

var oSheng = $("#sheng");

var dSheng = {head:[
        {text:"text - a",id:"a"},
        {text:"text - b",id:"b"}
    ]};
    oSheng.empty();//清空select下拉框

for(var i=0;i<dSheng.head.length;i++){
        $("<option value='" + dSheng.head[i].id + "'>" + dSheng.head[i].text + "</option>").appendTo(oSheng)//動态添加Option子項
    }

var dShi = {head:[
        {id:"sub - a - 1",value:"a1",parentid:"a"},
        {id:"sub - a - 2",value:"a2",parentid:"a"},
        {id:"sub - b - 1",value:"b1",parentid:"b"},
        {id:"sub - b - 2",value:"b2",parentid:"b"},
        {id:"sub - b - 3",value:"b3",parentid:"b"}
    ]}
var oShi = $("#shi")

    oSheng.change(function(){//添加onchange事件        
        oShi.empty();//清空下級下拉框        
        for(i=0;i<dShi.head.length;i++){                
if (dShi.head[i].parentid==oSheng.val())
            {                    
                $("<option value='" + dShi.head[i].value + "'>" + dShi.head[i].id + "</option>").appendTo(oShi)
            }                
        }        
    })
})
</script>

</head>
<body>
<select id="sheng">
<option value="a1">--------</option>
</select>

<select id="shi">
<option value="b1">????????</option>
</select>
</body>
</html>      

作者:菩提樹下的楊過

繼續閱讀