


jquery infinite cascading drop-down menu simple example demonstration_jquery
The examples in this article describe the code of jquery infinite cascading drop-down menu and the implementation ideas of jquery infinite cascading drop-down menu. Share it with everyone for your reference. The details are as follows:
Final rendering:
Because it is cascaded, the data must be in a tree structure. The test data here is as follows:
Look at the rendering:
1. Effect picture 1:
2. Effect picture two:
3. Effect picture three:
As can be seen from the picture, the number of drop-down boxes is not hard-coded, but dynamically loaded. Whenever the drop-down box selection changes, an ajax request will be sent, and the request will successfully return json format data. When the returned data is not empty (that is, when there are child nodes), a drop-down box will be added to the page. If not, then Not added.
The implementation code of the plug-in is as follows:
(function ($) { $.fn.CascadingSelect = function (options) { //默认参数设置 var settings = { url: "/Handler.ashx", //请求路径 data: "0", //初始值(字符串格式) split: ",", //分割符 cssName: "select", //样式名称 val: "id", //<option value="id">name</option> text: "name", //<option value="id">name</option> hiddenName: "selVal" //隐藏域的name属性的值 } //合并参数 if (options) $.extend(settings, options); //链式原则 return this.each(function () { init($(this), settings.data); /* 初始化 @param container 容器对象 @param data 初始值 */ function init(container, data) { //创建隐藏域对象,并赋初始值 var _input = $("<input type='hidden' name='" + settings.hiddenName + "' />").appendTo(container).val(settings.data); var arr = data.split(settings.split); for (var i = 0; i < arr.length; i++) { //创建下拉框 createSelect(container, arr[i], arr[i + 1] || -1); } } /* 创建下拉框 @param container 容器对象 @param parentid 父ID号 @param id 自身ID号 */ function createSelect(container, parentid, id) { //创建select对象,并将select对象放入container内 var _select = $("<select></select>").appendTo(container).addClass(settings.cssName); //如果parentid为空,则_parentid值为0 var _parentid = parentid || 0; //发送AJAX请求,返回的data必须为json格式 $.getJSON(settings.url, { parentid: _parentid }, function (data) { //添加子节点<option> addOptions(container, _select, data).val(id || -1) }); } /* 为下拉框添加<option>子节点 @param container 容器对象 @param select 下拉框对象 @param data 子节点数据(要求数据为json格式) */ function addOptions(container, select, data) { select.append($('<option value="-1">=请选择=</option>')); for (var i = 0; i < data.length; i++) { select.append($('<option value="' + data[i][settings.val] + '">' + data[i][settings.text] + '</option>')); } //为select绑定change事件 select.bind("change", function () { _onchange(container, $(this), $(this).val()) }); return select; } /* select的change事件函数 @param container 容器对象 @param select 下拉框对象 @param id 当前下拉框的值 */ function _onchange(container, select, id) { var nextAll = select.nextAll("select"); //如果当前select对象的值是空或-1(即:==请选择==),则将其后面的select对象全部移除 if (!id || id == "-1") { nextAll.remove(); } $.getJSON(settings.url, { parentid: id }, function (data) { if (data.length > 0) { var _html = $("<select class='" + settings.cssName + "'></select>"); var _select = addOptions(container, _html, data); //判断当前select对象后面是否跟有select对象 if (nextAll.length < 1) { select.after(_select); //没有则直接添加 } else { nextAll.remove(); //有则先移除再添加 select.after(_select); } } else { nextAll.remove(); //没有子项则后面的select全部移除 } saveVal(container); //进行数据保存,此方法必须放在回调函数里面 }); //saveVal(container); //如果放在这里,则会出现bug } /* 将选择的值保存在隐藏域中,用于表单提交保存 @param container 容器对象 */ function saveVal(container) { var arr = new Array(); arr.push(0); //为数组arr添加元素0,父节点从0开始,所以添加0 $("select", container).each(function () { if ($(this).val() > 0) { arr.push($(this).val()); //获取container下每个select对象的值,并添加到数组arr } }); //为隐藏域对象赋值 $("input[name='" + settings.hiddenName + "']", container).val(arr.join(settings.split)); } }); } })(jQuery);
I have tried my best to write the notes in detail, but I still need to explain some knowledge points.
1. My background language is C#, so the request path you see is like this (url: "/Handler.ashx"), you can use other There is no problem with the language, but the data returned through the ajax request must be in json format.
2. In the initialization method init(), we put a hidden field into the container. This hidden field is used to store values. We assign a value to it through a saveVal() method. The reason why we need to add a hidden field is because the data we choose will eventually be saved in the database, so there will be a form submission operation, so we add a hidden field.
3. The split separator in the default parameter settings (settings). The comma (,) is used here. You can also use other ones, such as (-) or (|). It is mainly used to split and combine the values of all drop-down boxes.
Splitting is mainly done during initialization (init). For example, the initial value (data) you give is not 0, but 0,1,4. At this time, it will be split and the create drop-down box method createSelect will be executed one by one. ()
Combination is mainly when assigning values to hidden fields, using separators to splice the values of each drop-down box into a string, and then assigning it to the hidden field.
4. {val: "id", text: "name" } in the default parameter settings (settings). They correspond to the corresponding attribute names in the json object you return.
5. There is a problem with writing the execution location of saveVal() in the _onchange() method. The reason why bugs occur when written outside the callback function is because $.getJSON() is asynchronous by default, and the saveVal() method is executed before the callback method is completed. Let’s take a look at where the bug is:
At this time, the value of the hidden field is wrong, and the correct value should be 0,1,5. Since the callback function has not been executed yet, that is, when nextAll.remove() has not been executed, saveVal()
is executed.Code of Html part of DEMO:
<html> <head> <title></title> <style type="text/css"> *{margin:0;padding:0;} #box{ width:500px; margin:100px auto;} .select{ width:120px; height:30px; margin-right:5px;} </style> </head> <body> <!--容器--> <div id="box"></div> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="Scripts/jquery.similar.cascadingselect.js" type="text/javascript"></script> <script type="text/javascript"> $("#box").CascadingSelect({data:"0,1,4"}); //设置初始值为0,1,4 </script> </body> </html>
The above is all the content of jquery to achieve the effect of infinite cascading drop-down menu. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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.

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.

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.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

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 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.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
