js操作xml实现下拉框联动

时间:2022-11-21 19:34:37

好久没写啦,懒啊。今天写点吧,希望对需要的人有帮助 

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    var oSelProvince;
    var oSelCity;
    function LD()
    {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.loadXML("<?xml version='1.0' encoding='utf-8' ?><China><province Name='湖南'><city>长沙</city><city>湘潭</city><city>浏阳</city></province><province Name='广东'><city>广州</city><city>深圳</city></province></China>");
        //xmlDoc.load(@"XML/info.xml");
        xmlDoc.async   =   false;  
        var root = xmlDoc.documentElement;
       
        oSelProvince = document.getElementById('selProvince');
        var oEmptyOption = document.createElement('option');
        oSelProvince.options.add(oEmptyOption);
        oEmptyOption.innerText = '';
       
        for(i=0;i<root.childNodes.length;i++)
        {  
            var province = xmlDoc.getElementsByTagName('province')[i].getAttribute('Name');
           
            var oOption = document.createElement('option');
            oSelProvince.options.add(oOption);
            oOption.innerText = province;
        }
       
        oSelProvince.onchange = function()
                                {  
                                    var province = oSelProvince.options[oSelProvince.selectedIndex].text;
                                    var node = xmlDoc.selectSingleNode("China/province[@Name='"+province+"']");
                                    var oSelCity = document.getElementById('selCity');
                                   
                                    oSelCity.length = 0;
                                   
                                    for(i=0; i<node.childNodes.length; i++)
                                    {                                 
                                        var oOption = document.createElement('option');
                                        oSelCity.options.add(oOption);
                                        oOption.innerText = node.childNodes[i].text;
                                    }
                                   
                                }
    }
    </script>
</head>
<body onload="LD()">
    <form id="form1" runat="server">
    <div>
    <select id="selProvince"></select>
    <select id="selCity"></select>
    </div>
    </form>
</body>
</html>