现在公司开发项目都是用jQuery,最近做联动下拉框时遇见个问题:在IE6下报错:“无法设置selected属性。未指明的错误”,而在其他浏览器中都顺利执行。
定位了下,是调用jQuery的val方法选中时出了问题,在调试时发现一个奇怪的现象,alert后是可以顺利执行的,于是尝试写个setTimeout延迟执行,结果可以解决问题。在网上找了下,原因如下:
“Note
that the error will only occur if you callappendChild,
then ask for theselect'schildNodes,
then set theselectedproperty
on the newly createdoption.
If you setselectedearlier,
either beforeappendChildor
after it, there's no problem. And if you omitchildNodes,
it works. The problem with jQuery is that its.val()function
loops overchildNodeslooking
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);
}
}
IE6下jQuery联动下拉框问题
本文解决了一个在Internet Explorer 6中使用jQuery进行下拉框联动时出现的问题,该问题表现为“无法设置selected属性”。通过分析jQuery源代码及采用setTimeout延迟执行的方法成功解决了这一兼容性难题。
798

被折叠的 条评论
为什么被折叠?



