search
HomeWeb Front-endJS TutorialOne article explains in detail how to implement three-level linkage menu with JS (with explanation of ideas)

Idea: Each drop-down menu, as a component, can receive a set of data and generate different menu options based on different data contents. The correlation between the three levels is achieved through event throwing. Data is obtained from the background.

When you click the province menu to select Shaanxi, the menu component will throw out the current province through event throwing. After knowing the province, you can obtain the city data under the province from the background. And so on. [Related recommendations: JavaScript video tutorial]

Achievement effect:

Front-end and back-end interface Information:

Three-level cascading menu interface:

## URL: http://10.9.72.245:4010

## Method: "GET"

## Data format:

Request: QueryString

Response: JSON

Interface name:

1. http:// 10.9.72.245:4010/getProvince

2. http://10.9.72.245:4010/getCity

3. http://10.9.72.245:4010/getCounty

Get province interface

Interface name:/getProvince

Request: No parameters

Response: {"province":["Beijing","Tianjin","Hebei" ,...]}

Get city interface:

Interface name:/getCity

Request:?province="Hebei"

Response: { "city":["Shijiazhuang", "Tangshan", "Qinhuangdao",...]}

Get county interface:

Interface name:/getCounty

Request :?city="Shijiazhuang"

Response: {"county":["Chang'an District", "Qiaodong District", "Qiaoxi District",...]}

Specific implementation :

1. Create drop-down menu component and front-end and back-end communication:

<!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 &#39;./js/QueryString.js&#39;;
        import DropDownMemu from &#39;./js/DropDownMemu.js&#39;;
 
        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",
        })
    }
}

3. Component parent class:

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 background service:

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. Server data is stored in city.json in json format, as shown below:

{

"Beijing": {

"Beijing": ["Dongcheng District", "Xicheng District", "Chongwen District", "Xuanwu District", "Chaoyang District", "Fengtai District", "Shijingshan District", "Haidian District", "Mentougou District", "Fangshan District", "Tongzhou District", "Shunyi District", "Changping District", "Daxing District", "Pinggu District", "Huairou District", "Miyun County", "Yanqing County", "Others"]

},

"Tianjin": {

"Tianjin": ["Heping District", "Hedong District", "Hexi District", "Nankai District", "Hebei District", "Hongjie District", "Binhai New District", "Dongli District", "Xiqing District", "Jinnan District", "Beichen District", "Ninghe District", "Wuqing District", "Jinghai County", "Baodi District", "Jixian", "Tanggu District", "Hangu District" ", "Dagang District", "Baodi District", "Others"]

},

}

The above is the detailed content of One article explains in detail how to implement three-level linkage menu with JS (with explanation of ideas). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment