问题描述:firefox下js中动态组装select时指定option的selected属性的失效
有问题的代码如下:
1 // 加载select列表
2 var teaOption ='', ownerSel = $("ownerSel");
3 for(var i = 0; i < teaList.length; i ++){
4 var teacher = teaList[i];
5 if(teacher.isDeleted === false){
6 var tid = teacher.id, tName = teacher.fullName, newOption;
7 var flag = ((tid === formerOwnerId) ? 'selected="selected"' : '');
9 teaOption += '<option value="'+tid+'" '+ flag +'>'+ tName +'</option>';
10 }
11 }
12 ownerSel.html(teaOption);
2 var teaOption ='', ownerSel = $("ownerSel");
3 for(var i = 0; i < teaList.length; i ++){
4 var teacher = teaList[i];
5 if(teacher.isDeleted === false){
6 var tid = teacher.id, tName = teacher.fullName, newOption;
7 var flag = ((tid === formerOwnerId) ? 'selected="selected"' : '');
9 teaOption += '<option value="'+tid+'" '+ flag +'>'+ tName +'</option>';
10 }
11 }
12 ownerSel.html(teaOption);
此时selected属性无效,ff中的select显示的是option列表的最后一个。
原因貌似是这样子:
selected这个属性本身是没有错的,你在页面开始加载的前写好,然后浏览器加载的时候就会读取这个dom,然后有selected这个效果。
但是通过js动态组装的select的html代码,在ie下我刚刚试了下可行(我刚刚失败的原因是三目运算符处少加了一个括号);firefox下,在请求加载的同时加载dom元素,但是ff内核可能是为了追求速度,而省略了一些dom的属性的加载,导致了selected这个属性的失效。
解决方法(我用的是mootools):在加载的时候将option元素通过如下解决
1 // 加载select列表
2 var ownerSel = $("ownerSel");
3 for(var i = 0; i < teaList.length; i ++){
4 var teacher = teaList[i];
5 if(teacher.isDeleted === false){
6 var tid = teacher.id, tName = teacher.fullName, newOption;
7 if(tid === formerOwnerId)
8 newOption = new Element('option', {"value" : tid, "selected" : "selected"}).html(tName);
9 else
10 newOption = new Element('option', {"value" : tid}).html(tName);
11 ownerSel.grab(newOption); // 将新的element插入到select中
12 }
13 }
2 var ownerSel = $("ownerSel");
3 for(var i = 0; i < teaList.length; i ++){
4 var teacher = teaList[i];
5 if(teacher.isDeleted === false){
6 var tid = teacher.id, tName = teacher.fullName, newOption;
7 if(tid === formerOwnerId)
8 newOption = new Element('option', {"value" : tid, "selected" : "selected"}).html(tName);
9 else
10 newOption = new Element('option', {"value" : tid}).html(tName);
11 ownerSel.grab(newOption); // 将新的element插入到select中
12 }
13 }