Home >Web Front-end >JS Tutorial >JQuery implementation of cascading drop-down box effect example explanation_jquery
Use JQuery and select to realize the linkage between car manufacturers and car types. The reference process is as follows
Rendering:
Logic analysis diagram:
html code:
<!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="JQuery implementation of cascading drop-down box effect example explanation_jquery"/> </span> <span class="cartype"> 汽车类型: <select></select> </span> </div> </body> </html>
css code:
.car { text-align:center; } .cartype{ display:none; }
js code:
$(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(); } }); });
The above is a small example of using JQuery and select to implement cascading drop-down boxes. I hope it will be helpful to everyone's learning.