用xml实现省份城市的级联(无刷新的)

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>无标题页</title>
</head>
<script type="text/javascript" >
<!--
var xmldom = new ActiveXObject("Microsoft.XMLDOM");
var arrProvince = [];//创建数组存放从city.xml读来的省份数据
var arrCitiy = [];//创建数组存放从city.xml读来的城市数据
function init()
{
    xmldom.async = true;

  //当状态发生变化的时候重新调用statInit方法;
    xmldom.onreadystatechange = statInit;
    window.setTimeout(function()
    {//加载city.xml
        xmldom.load("city.xml");
    }
    , 10);
}

function statInit()
{

//xmldom.readyState:

    if (xmldom.readyState == 4)
    {
        if (xmldom == null || xmldom.documentElement == null)
        {
            alert("XML文件不存在或没有菜单项");
            return ;
        }
        createProvince();
    }
}

function createProvince()
{
    var xmlprovinces = xmldom.getElementsByTagName("province");
//    delitem(document.all.province);//清除各个选项,防止在重新加载
//    delitem(document.all.city);这两句没必要,删除即可
    for (var i = 0; i < xmlprovinces.length; i++)
    {
          arrProvince[i] = xmlprovinces[i].getAttribute("name");
          arrCitiy[i] = xmlprovinces[i].getAttribute("cities");
          document.getElementById("province").options.add(window.Option(arrProvince[i], arrProvince[i]));
   //       document.all.province.add(window.Option(arrProvince[i], arrProvince[i]));//添加各个option选项
//          window.Option(province[i], province[i])创建option选项
    }
    provinceChange(0);
}

function provinceChange(index)
{
    var city = arrCitiy[index].split(" ");
    delitem(document.all.city); //清除上次的列表
    for (var i = 0; i < city.length; i++)
    {
//    alert(i);
      document.all.city.add(window.Option(city[i], city[i]));
    }
}

function delitem(options)
{
    optioncount = options.length;
    for (i = optioncount - 1; i >= 0; i--)
    {
        options.options[i] = null
    }
}
//-->
</script>

 

<body onload="init()">
<select name="province" onchange="provinceChange(this.selectedIndex)"></select>
<select name="city"></select>
</body>
</html>

你可能感兴趣的:(xml)