级联选择框是一种独特的选择机制,对于从大列表中选择项目特别有用。Cascader是一个实现此功能的jQuery插件。
这个jQuery插件从JS对象数组中生成一个用户友好的多列级联下拉列表,并允许您将其附加到文档中的任何文本字段。灵感来自Element UI和Ant Design的Cascader组件。
1.在文档中加载jQuery库和Cascader插件的文件。
<link rel="stylesheet" href="/path/to/cascader.css" /> <script src="/path/to/cdn/jquery.slim.min.js"></script> <script src="/path/to/cascader.js"></script>
2.在JS对象数组中准备数据,如下所示:
// languages.js var languages = [ { "indexcode": "1", "name": "Front-End", "s": [ { "indexcode": "11", "name": "HTML", "s": [ { "indexcode": "111", "name": "HTML" }, { "indexcode": "112", "name": "XML" }, { "indexcode": "113", "name": "HTML5" }, ] }, { "indexcode": "12", "name": "CSS", "s": [ { "indexcode": "121", "name": "CSS" }, { "indexcode": "122", "name": "CSS3" }, { "indexcode": "123", "name": "CSS4" }, ] }, { "indexcode": "13", "name": "JavaScript", "s": [ { "indexcode": "131", "name": "jQuery" }, { "indexcode": "122", "name": "Angular" }, { "indexcode": "123", "name": "React" }, ] }, ] }, { "indexcode": "2", "name": "Back-End", "s": [ { "indexcode": "21", "name": "C", "s": [ { "indexcode": "211", "name": "C" }, { "indexcode": "212", "name": "C++" }, { "indexcode": "213", "name": "C#" }, ] }, { "indexcode": "22", "name": "Database", "s": [ { "indexcode": "221", "name": "MySql" }, { "indexcode": "222", "name": "SQL" }, { "indexcode": "223", "name": "Oracle" }, ] }, { "indexcode": "23", "name": "Others", "s": [ { "indexcode": "231", "name": "Node.js" }, { "indexcode": "122", "name": "Python" }, { "indexcode": "123", "name": "Ruby" }, ] }, ] } ]
3.导入数据JavaScript。
<script src="./languages.js"></script>
4.生成一个级联下拉列表,并将其附加到一个输入字段。
<input type="text" id="test"/>
// parse data languages.forEach(function(item){ item.label = item.name item.value = item.indexcode item.children = item.s item.s.forEach(function(item2){ item2.label = item2.name item2.value = item2.indexcode if (item2.s && item2.s.length) { item2.children = item2.s item2.s.forEach(function(item3){ item3.label = item3.name item3.value = item3.indexcode }) } }) }) // initialize $('#test').zdCascader({ data: languages, container: '#test', onChange: function(value, label, datas){ console.log(value, label, datas); } });