用JQuery和select来实现汽车厂商和汽车类型的联动,参考过程如下
效果图:
逻辑分析图:
html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>级联下拉框效果</title> <link rel="stylesheet" type="text/css" href="css/chainselect.css"> <script language="javascript" type="text/javascript" src="js/jquery.js"></script> <script language="javascript" type="text/javascript" src="js/chainselect.js"></script> </head> <body> <div class="car"> <span class="carname"> 汽车厂商: <select> <option value="">请选择汽车厂商</option> <option value="BMW">宝马</option> <option value="Audi">奥迪</option> <option value="VW">大众</option> </select> <img src="images/pfeil.gif" alt="有数据"/> </span> <span class="cartype"> 汽车类型: <select></select> </span> </div> </body> </html>
css代码:
.car { text-align:center; } .cartype{ display:none; }
js代码:
$(document).ready(function(){ //找到下拉框 var carnameSelect = $(".carname").children("select"); var cartypeSelect = $(".cartype").children("select"); //给下拉框注册事件 carnameSelect.change(function(){ var carnameValue = $(this).val(); if( carnameValue != ""){ //carnameValue不为空的情况接着判断 if(!carnameSelect.data(carnameValue)){ //不在缓冲区中,需要向服务器请求 $.post("ChainSelect",{keyword:carnameValue,type:"top"},function(data){ if (data.length != 0){ //返回的数据不为空 cartypeSelect.html(""); $("<option value=''>请选择汽车类型</option>").appendTo(cartypeSelect); for(var i = 0;i < data.length; i++ ){ $("<option value =' " + data[i] + " '> "+ data[i] +"</option>").appendTo(cartypeSelect); } cartypeSelect.parent().show(); carnameSelect.next().show(); }else{ //返回的数据为空 cartypeSelect.parent().hide(); carnameSelect.next().hide(); } carnameSelect.data(carnameValue,data); },"json"); }else{ //在缓冲区中 var data = carnameSelect.data(carnameValue); if (data.length != 0){ //返回的数据不为空 cartypeSelect.html(""); $("<option value=''>请选择汽车类型</option>").appendTo(cartypeSelect); for(var i = 0;i < data.length; i++ ){ $("<option value =' " + data[i] + " '> "+ data[i] +"</option>").appendTo(cartypeSelect); } cartypeSelect.parent().show(); carnameSelect.next().show(); }else{ //返回的数据为空 cartypeSelect.parent().hide(); carnameSelect.next().hide(); } } }else{ //carnameValue为空的情况,隐藏第二个下拉框 cartypeSelect.parent().hide(); carnameSelect.next().hide(); } }); });
以上就是利用JQuery和select实现级联下拉框的小例子,希望对大家的学习有所帮助。