思路:每一个下拉菜单作为一个组件,可以接收一组数据,根据数据内容不同生成不同的菜单选项。三级之间的关联通过事件抛发来实现。数据从后台获取。
当点击省份菜单选择陕西时,菜单组件会通过事件抛发把当前的省份抛发出来。得知省份之后就可以从后台获取省份下面的城市数据。依次类推。【相关推荐:javascript视频教程】
实现效果:
前后端接口信息:三级级联菜单接口:## url:http://10.9.72.245:4010
## method: get
## 数据格式:
请求:querystring
响应:json
接口名称: 1、http://10.9.72.245:4010/getprovince
2、http://10.9.72.245:4010/getcity
3、http://10.9.72.245:4010/getcounty
获取省份接口 接口名:/getprovince
请求:无参数
响应:{province:[北京,天津,河北,...]}
获取城市接口: 接口名:/getcity
请求:?province=河北
响应:{city:[石家庄, 唐山, 秦皇岛,...]}
获取县接口: 接口名:/getcounty
请求:?city=石家庄
响应:{county:[长安区, 桥东区, 桥西区,...]}
具体实现:1、创建下拉菜单组件及前后端通信:<!doctype html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>document</title></head><body> <script type="module"> import querystring from './js/querystring.js'; import dropdownmemu from './js/dropdownmemu.js'; let cityinfo = {}; init(); function init(){ ajax("http://10.9.72.245:4010","getprovince").then(succesefunction).catch(failfunction); } // ajax通信成功后执行: function succesefunction(_data){ let data = json.parse(_data); let key = object.keys(data)[0]; data = object.values(data)[0]; if(dropdownmemu.obj[key]){ dropdownmemu.obj[key].list = data; dropdownmemu.obj[key].name = data[0]; }else{ let memu = new dropdownmemu(key); memu.addeventlistener("change",changehandler); memu.list = data; memu.name =data[0]; memu.appendto("body"); cityinfo[key] = data[0]; } } // 当菜单显示内容改变时接收到菜单抛发出的事件并获取事件中携带的信息例如{"province":"陕西"}或者{"city":"西安"} function changehandler(e){ let key = e.currenttarget.label; cityinfo[key] = e.data[key]; let interfacename; if(e.data.province){ interfacename = "getcity"; }else if(e.data.city){ interfacename = "getcounty"; }else{ return } ajax("http://10.9.72.245:4010",interfacename,cityinfo).then(succesefunction).catch(failfunction); } /* ajax通信: 参数列表: url: 后台服务地址 interfacetype:接口类型,如 "getprovince" data:传输的数据,例如:{"province":"陕西"} 通信类型type:默认"get"请求 是否以json格式发送数据:默认为false */ function ajax(url,interfacetype,data,type="get",json=false){ type = type.touppercase(); let o = type==="get"? null : data; if(data) data = json? json.stringify(data) : querystring.stringify(data); else data = ""; return new promise(function(resolve,reject){ let xhr = new xmlhttprequest(); xhr.open(type,url + "/" + interfacetype + (type==="get"? "?"+data : "")); xhr.send(o); xhr.onreadystatechange = function(){ if(xhr.readystate===4 && xhr.status===200){ resolve(xhr.response); }else if(xhr.readystate===4){ resolve(xhr.status); } } xhr.onerror= function(){ reject(xhr.response); } }) } // ajax通信失败时执行 function failfunction(_err){ console.log(_err); } </script></body></html>
2、下拉菜单组件:dropdownmemu类import component from "./component.js";export default class dropdownmemu extends component { _list; // 当前下拉菜单的可选项。 _name; // 当前选择显示的名字例如: "北京" label; // 当前下拉菜单的标签,province city county spanlabel; // 标签容器 spancaret; // 三角形 ul; // 下拉选项容器 bool=false; // 控制鼠标事件,聚焦状态或正在选择时,不触发鼠标划入滑出效果。 // 根据不同的状态设置下拉菜单的样式。 static dropdown = symbol(); static default = symbol(); // 静态全局变量 每创建一个下拉菜单,都存储到这个对象中,全局管理创建的每一个下拉菜单。 static obj = {}; constructor(_label) { super("p"); this.label = _label; // 创建html结构 this.render(); // 设置样式 this.setstyle(); // 鼠标滑入滑出点击,聚焦失焦,点击事件 this.elem.addeventlistener("focusin", e =>this.mousehandler(e)); this.elem.addeventlistener("focusout", e =>this.mousehandler(e)); this.elem.addeventlistener("mouseenter", e=>this.mousehandler(e)); this.elem.addeventlistener("mouseleave", e=>this.mousehandler(e)); this.elem.addeventlistener("click", e => this.mousehandler(e)); } mousehandler(e){ switch(e.type){ case "mouseenter": if(this.bool) return this.elem.style.backgroundcolor = "#e6e6e6"; break; case "mouseleave": if(this.bool) return this.elem.style.backgroundcolor = "#fff"; break; case "focusin": this.setstate(dropdownmemu.dropdown); this.bool = true; break; case "focusout": this.setstate(dropdownmemu.default); this.bool = false; case "click" : if(e.target.constructor !== htmllielement) return this._name = e.target.textcontent; // 当点击时修改当前显示的内容,重设样式,并抛发事件告知外部当前的内容。 this.setcontent(); let evt = new focusevent("focusout"); this.elem.dispatchevent(evt); } } set name(_name){ this._name = _name; this.setcontent(); } get name(){ return this._name; } set list(_list){ this._list = _list; this.ul.innerhtml = ""; this.ul.appendchild(this.createli()); } // 修改菜单当前显示的内容并并抛发数据 setcontent(_name){ this._name = _name || this._name; this.spanlabel.textcontent = this._name; let evt = new mouseevent("change"); if(!evt.data) evt.data = {} evt.data[this.label] = this._name; this.dispatchevent(evt); } // 根据指定的list创建下拉菜单选项。 createli(_list){ this._list = _list || this._list; let elem = document.createdocumentfragment(); this._list.foreach((item, index) => { let li = document.createelement("li"); li.textcontent = item; object.assign(li.style, { lineheight:"26px", padding:"0 15px", }) elem.appendchild(li); }) return elem; } setstate(type){ switch(type){ case dropdownmemu.dropdown: this.elem.style.backgroundcolor = "#e6e6e6"; this.ul.style.display = "block"; break; case dropdownmemu.default: this.elem.style.backgroundcolor = "#fff"; this.ul.style.display = "none"; break; } } appendto(parent){ super.appendto(parent); dropdownmemu.obj[this.label] = this; } render() { this.elem.setattribute("tabindex",1); this.spanlabel = document.createelement("span"); this.spancaret = document.createelement("span"); this.ul = document.createelement("ul"); this.elem.appendchild(this.ul); this.spanlabel.textcontent = this._name; this.elem.appendchild(this.spanlabel); this.elem.appendchild(this.spancaret); } setstyle() { object.assign(this.elem.style, { float: "left", minheight: "20px", minwidht: "80px", color: "#333", fontweight: "normal", textalign: "center", whitespace: "nowrap", verticalalign: "middle", cursor: "pointer", border: "1px solid #ccc", borderradius: "4px", backgroundcolor: "#fff", padding: "6px 12px", fontsize: "14px", userselect: "none", marginright: "100px", position:"relative", }); object.assign(this.spanlabel.style, { float: "left", padding: "0 5px" }) object.assign(this.spancaret.style, { display: "inline-block", verticalalign: "middle", bordertop: "4px dashed", borderright: "4px solid transparent", borderleft: "4px solid transparent", }) object.assign(this.ul.style, { liststyle: "none", position: "absolute", top: "100%", left: "0", zindex: "1000", minwidth: "100px", padding: "5px 0px", margin: "2px 0 0", fontsize: "14px", textalign: "left", backgroundcolor: "#fff", border: "1px solid rgba(0, 0, 0, 0.15)", borderradius: "4px", boxshadow: "0 6px 12px rgba(0, 0, 0, 0.175)", display: "none", }) }}
3、component 父类:export default class component extends eventtarget{ elem; constructor(_type){ super(); this.elem = this.createelem(_type); } createelem(_type){ let elem = document.createelement(_type); return elem; } appendto(parent){ if(typeof parent==="string") parent = document.queryselector(parent); parent.appendchild(this.elem); }}
4、nodejs后台服务:let http = require("http");let querystring = require("querystring");let data, req, res;// 读取所有城市数据并解析为对象,同步读取。let fs = require("fs");let allcityinfo = json.parse(fs.readfilesync('./city.json'));let server = http.createserver(listenerhandler);server.listen(4010,"10.9.72.245",listenerdonehandler);function listenerhandler(_req,_res){ req = _req; res = _res; res.writehead(200,{ "content-type":"text/html;charset=utf-8", "access-control-allow-origin":"*", "access-control-allow-headers":"*", }); data=""; req.on("data",function(_data){ data=_data; }) req.on("end",receivehandler);}function receivehandler(){ // console.log(allcityinfo); // 根据请求头的url解析接口类型 let type = req.url.trim().split("?")[0].replace(/\//g,""); console.log(type); // 根据请求头的url解析传入的参数 if(req.method.touppercase()==="get"){ if(req.url.includes("favicon.ico")) return res.end(); else data = req.url.includes("?") ? req.url.split("?")[1] : ""; } try{ data = json.parse(data); }catch{ data = querystring.parse(data); } console.log(data); // 根据接口类型查找数据。 let list = {}; switch(type){ case "getprovince": list.province = object.keys(allcityinfo); break; case "getcity" : list.city = object.keys(allcityinfo[data.province]); break; case "getcounty": list.county = allcityinfo[data.province][data.city]; break; } console.log(list); res.write(json.stringify(list)); res.end()}function listenerdonehandler(){ console.log("开启服务成功");}
5、服务端数据以json格式存储在city.json中,如下所示:{
北京: {
北京: [东城区, 西城区, 崇文区, 宣武区, 朝阳区, 丰台区, 石景山区, 海淀区, 门头沟区, 房山区, 通州区, 顺义区, 昌平区, 大兴区, 平谷区, 怀柔区, 密云县, 延庆县, 其他]
},
天津: {
天津: [和平区, 河东区, 河西区, 南开区, 河北区, 红挢区, 滨海新区, 东丽区, 西青区, 津南区, 北辰区, 宁河区, 武清区, 静海县, 宝坻区, 蓟县, 塘沽区, 汉沽区, 大港区, 宝坻区, 其他]
},
}
以上就是一文详解js实现三级联动菜单(附思路说明)的详细内容。