现在公司开发项目都是用jQuery,最近做联动下拉框时遇见个问题:在IE6下报错: “无法设置selected属性。未指明的错误”,而在其他浏览器中都顺利执行。
定位了下,是调用jQuery的val方法选中时出了问题,在调试时发现一个奇怪的现象,alert后是可以顺利执行的,于是尝试写个setTimeout延迟执行,结果可以解决问题。在网上找了下,原因如下:
“Note that the error will only occur if you call appendChild, then ask for the select's childNodes, then set the selectedproperty on the newly created option. If you set selected earlier, either before appendChild or after it, there's no problem. And if you omit childNodes, it works. The problem with jQuery is that its .val() function loops over childNodes looking for an option to set, and thus always triggers the bug.”
顺便看了下jQuery(1.8.0)源代码:
set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values;}
看来也只能用setTimeout的方式解决了,于是封装了个方法:
setSelectVal:function(sel,value){ if($.browser.msie && $.browser.version=="6.0") { setTimeout(function(){ sel.val(value); },1); }else { sel.val(value); } }