下边是读取json填充select标签,因为分类是无限的,所以采用js的递归方法:
var json = { "parents": [ { "name": "餐饮", "childrens": [ { "name": "小吃", "childrens": [ { "name": "东北小吃" } ] }, { "name": "大吃" } ] }, { "name": "酒店" }, { "name": "度假村", "childrens": [{ "name": "海南" }, { "name":"三亚", "childrens": [] } ] } ] };
(关于json和字符串的转换,请查看:http://camnpr.com/archives/json2.html)
var flag = "", parent = json.parents;
fillSelect(parent);
function fillSelect(pr, f) {
for (var i = 0, len = pr.length; i < len; i++) {
$("#mysl").addOption((f || "") + (pr[i].childrens && pr[i].childrens.length || pr == parent ? "┣" : "┗") + pr[i].name, pr[i].name);
if (pr[i].childrens) { flag += " "; fillSelect(pr[i].childrens, flag); } flag = ""; }
}
<select id="mysl"><option value="0">全部</option></select>
(说明:addOption:方法是jquery一个组件jquery.select.js 搜索可以找到的,找不到就联系我qq)
运行后的效果如下:
select的optgroup选项,也可以分组展示选项。下边是动态创建optgroup的方法和注意事项:
var select1 = document.getElementById("mysl");
var group=document.createElement('OPTGROUP');
group.label = "optiongroup1";
select1.appendChild(group);
select1.options.add(new Option("option1","1");
select1.options.add(new Option("option2","2");
生成的HTML代码为:
<select name="select1" id="select1">
<optgroup label="optiongroup1"></optgroup>
<option value="1">option1</option>
<option value="2">option2</option>
</select>
倒也不影响显示,关键是safari下,optgroup标签不显示了,
整了我好久,最后发现,optgroup闭紧了,只要结束标签前有个什么都能显示。即:
<optgroup label="optiongroup1"><!--这里随便有个字符--></optgroup>
于是我构造时插入空格:
var group=document.createElement('OPTGROUP');
group.label = "optiongroup1";
group.innerText= " ";
select1.appendChild(group);
终于支持IE,Firefox, opera, safari, chrome了。