您好,登錄后才能下訂單哦!
這篇“怎么使用JS實現三級聯動菜單”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內容,內容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“怎么使用JS實現三級聯動菜單”文章吧。
思路:每一個下拉菜單作為一個組件,可以接收一組數據,根據數據內容不同生成不同的菜單選項。三級之間的關聯通過事件拋發來實現。數據從后臺獲取。
當點擊省份菜單選擇陜西時,菜單組件會通過事件拋發把當前的省份拋發出來。得知省份之后就可以從后臺獲取省份下面的城市數據。依次類推。
實現效果:
## 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":["長安區", "橋東區", "橋西區",...]}
<!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>
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", }) } }
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); } }
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("開啟服務成功"); }
{
"北京": {
"北京": ["東城區", "西城區", "崇文區", "宣武區", "朝陽區", "豐臺區", "石景山區", "海淀區", "門頭溝區", "房山區", "通州區", "順義區", "昌平區", "大興區", "平谷區", "懷柔區", "密云縣", "延慶縣", "其他"]
},
"天津": {
"天津": ["和平區", "河東區", "河西區", "南開區", "河北區", "紅撟區", "濱海新區", "東麗區", "西青區", "津南區", "北辰區", "寧河區", "武清區", "靜海縣", "寶坻區", "薊縣", "塘沽區", "漢沽區", "大港區", "寶坻區", "其他"]
},
}
以上就是關于“怎么使用JS實現三級聯動菜單”這篇文章的內容,相信大家都有了一定的了解,希望小編分享的內容對大家有幫助,若想了解更多相關的知識內容,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。