Home  >  Article  >  Web Front-end  >  Using JavaScript to implement infinite cascading menu processing

Using JavaScript to implement infinite cascading menu processing

WBOY
WBOYOriginal
2023-06-15 21:09:481737browse

Infinite cascading menu is a very common front-end interaction method and is widely used in many scenarios. This article will introduce to you how to use JavaScript to implement infinite cascading menus. I hope it will be helpful to you.

1. Implementation Ideas

The idea of ​​implementing infinite cascading menus on the front end can be summarized as:

  1. Define the data source: usually a JSON object, used to Store all levels of menu data;
  2. Dynamic rendering of menus: when a certain level of options is selected, the next level of menus are dynamically generated;
  3. Realize linkage effects: when a certain level of options is selected When selecting an option, the menu at the next level must be updated in a timely manner and change the available options according to the selected option.

The specific implementation ideas are as follows:

  1. Define an array to store the value selected at each level;
  2. Define multiple Select tags are used to display menus at each level;
  3. Bind a change event to each select tag. When one of the options is selected, update the value at the corresponding position in the array and generate the next select tag. , and render the next level's optional options based on the previous level's options;
  4. Loops to generate all levels of select tags and insert them into the DOM.

2. Code Implementation

The process of implementing infinite cascading menus mainly involves two parts, namely the layout of the HTML page and the writing of JavaScript code. Next, let’s take a look at the implementation details of the two parts respectively.

  1. HTML page layout

In the HTML page, we need to create multiple select tags to display menus at each level. At the same time, you also need to bind a change event to each select tag to implement dynamic updating of the menu.

<body>
    <form>
        <select id="province" onchange="changeProvince()">
            <option value="">请选择省份</option>
            <option value="1">浙江</option>
            <option value="2">江苏</option>
        </select>
        <select id="city" onchange="changeCity()"></select>
        <select id="area"></select>
    </form>
</body>
  1. JavaScript code implementation

In the JavaScript code, you need to define a JSON object to store all levels of menu data. After selecting an option at a certain level, the menu at the next level is dynamically generated and the available options are changed according to the selected option. The specific implementation is as follows:

var menuData = {
    "province": {
        "1": "杭州市",
        "2": "温州市"
    },
    "city": {
        "1": {
            "11": "西湖区",
            "12": "江干区"
        },
        "2": {
            "21": "鹿城区",
            "22": "瓯海区"
        }
    },
    "area": {
        "11": {
            "111": "西溪湿地",
            "112": "灵隐寺"
        },
        "12": {
            "121": "杭州大厦",
            "122": "江干公园"
        },
        "21": {
            "211": "南湖",
            "212": "红旗广场"
        },
        "22": {
            "221": "瓯海公园",
            "222": "龙湾湾国际商务区"
        }
    }
}

var level = ["province", "city", "area"];
var selectedValue = ["", "", ""];

function init() {
    generateMenu("province", "1");
}

function changeProvince() {
    selectedValue[0] = document.getElementById("province").value;
    document.getElementById("city").innerHTML = "";
    document.getElementById("area").innerHTML = "";
    generateMenu("city", selectedValue[0]);
}

function changeCity() {
    selectedValue[1] = document.getElementById("city").value;
    document.getElementById("area").innerHTML = "";
    generateMenu("area", selectedValue[1]);
}

function generateMenu(currentLevel, currentValue) {
    var select = document.createElement("select");
    select.setAttribute("id", currentLevel);
    select.setAttribute("onchange", "change" + currentLevel.charAt(0).toUpperCase() + currentLevel.slice(1) + "()");

    var option = document.createElement("option");
    option.setAttribute("value", "");
    option.innerHTML = "请选择" + currentLevel;
    select.appendChild(option);

    var submenu = menuData[currentLevel];
    for (var key in submenu) {
        if (submenu[key] != null) {
            var option = document.createElement("option");
            option.setAttribute("value", key);
            option.innerHTML = submenu[key];
            select.appendChild(option);
        }
    }

    document.getElementById(currentLevel).appendChild(select);
    if (currentValue != "") {
        document.getElementById(currentLevel).value = currentValue;
        if (level.indexOf(currentLevel) < level.length - 1) {
            var nextLevel = level[level.indexOf(currentLevel) + 1];
            generateMenu(nextLevel, selectedValue[level.indexOf(nextLevel)]);
        }
    }
}

init();

In this code, a JSON object menuData containing menu data for each level and an array level are first defined to store the identifiers of each level. At the same time, an array selectedValue is also defined to store the selected values ​​at each level. After that, an init function is defined to initialize the first-level menu, that is, the menu for generating provinces.

Next, two functions, changeProvince and changeCity, are defined, which are used to update the values ​​of the selected province and city, and regenerate the next level menu.

Finally, the generateMenu function is defined, which is used to generate the current level menu and make recursive calls to the next level. In the process of generating the menu, the select tag is generated and the corresponding option is added, and added to the DOM after each menu rendering is completed. If the current level is not the last level, then a recursive call is made based on the currently selected value until all levels of menus are generated.

3. Summary

Through the implementation of the above code, we can see that it is not difficult to implement infinite cascading menus in JavaScript. The implementation method introduced in this article is a relatively basic implementation method. For different needs, it needs to be adjusted accordingly according to the actual situation.

Of course, there are already some relatively mature third-party libraries that can be used to implement unlimited cascading menus, such as jQuery and Vue.js, which can implement this function more conveniently. However, we should still understand the use of these libraries on the basis of mastering the principles, so that we can use these tools more flexibly to complete various complex tasks.

The above is the detailed content of Using JavaScript to implement infinite cascading menu processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn