1. 程式人生 > >Jquery實現ajax三級聯動

Jquery實現ajax三級聯動

$(function(){ $.ajax( { url:'./Provinces.xml', type:'get', dataType:'xml', success:function(msg){ $(msg).find('Province').each(function(k,v){ var name = $(v).attr('ProvinceName'
); var id = $(v).attr('ID'); $('select:eq(0)').append('<option value='+id+'>'+name+'</option>'); }); } } ); //將第三個select清空 $('select:eq(0)').bind('change',function
(){
$('select:eq(2)').empty(); $('select:eq(2)').append('<option value=0>select</option>'); }); $('select:eq(0)').bind('change',function(){ //獲得第一個select的ID var num = $('select:eq(0) option:selected').attr('value'
); //每次都要進行清空 $('select:eq(1)').empty(); $('select:eq(1)').append('<option value=0>select</option>'); $.ajax( { url:'./Cities.xml', type:'get', dataType:'xml', success:function(msg){ $(msg).find('City[PID='+num+']').each(function(k,v){ var name = $(v).attr('CityName'); var id = $(v).attr('ID'); $('select:eq(1)').append('<option value='+id+'>'+name+'</option>'); }); } } ); }); $('select:eq(1)').bind('change',function(){ var num = $('select:eq(1) option:selected').attr('value'); // console.log(num); $('select:eq(2)').empty(); $.ajax( { url:'./Districts.xml', type:'get', dataType:'xml', success:function(msg){ $(msg).find('District[CID='+num+']').each(function(k,v){ var name = $(v).attr('DistrictName'); var id = $(v).attr('ID'); $('select:eq(2)').append('<option value='+id+'>'+name+'</option>'); }); } } ); }); });