/** * Generate the option tree control based on JSON data * If a children node is automatically generated tree data * @param {JSON} data * @param {int} n node Depth * @param {string} char node Name prefix * @returns {string} * @since 1.0 2014-8-22 by Sutroon * @example * var data = (typeof (data) = = "Object")? Data: $.parsejson (data); * var str = '; * Str=generate_options (data); */functionGenerate_options (data, N,Char) { if(n = =undefined) {N= 0; } if(Char==undefined) { Char= ' ... '; } varPad = '; while(N > 0) {Pad+=Char; N--; } varstr = "; if(data.length) {//multi-line format for(vari = 0; i < data.length; i++) { if(data[i].id) {//for [{"id": "1", "name": "Name1"}] formatstr + = ' <option value= ' + data[i].id + ' > ' + Pad + (data[i].name? Data[i].name:data[i].text) + ' </option> '; } Else if(data[i].item) {//for [{"Item": "1"},{"item": "2"}]str + = ' <option value= "' + Data[i].item + '" > ' + pad + data[i].item + ' </option> '; } Else { //format for {"Item1", "item2"}str + = ' <option value= "' + data[i] + '" > ' + Pad + data[i] + ' </option> '; } if(data[i].children) {str+ = Generate_options (Data[i].children, n + 1,Char); } } } Else { //for {"A": "A1", "B": "B2"} single-line format for(varattrinchdata) {STR+ = ' <option value= ' + attr + ' "> ' + data[attr] + ' </option> '; } } returnstr;}
Copyright NOTICE: This article is the original Tian Lan (14507247#qq.com), copyright follow the Knowledge sharing license agreement [view]. You can freely reprint the collection, but please leave this statement, thank you!
JavaScript Several methods of looping about JSON collections