您的位置:首页 > Web前端 > JQuery

IE6 jQuery 操作 select的BUG

2012-10-12 14:04 369 查看

在给select初始化的时候,除了ie 6外的所有浏览器中都正常显示效果(ie7,8,9,
firefox, chrome), IE6下提示“无法设置selected属性,未指明的错误”或者就是根本就没有显示。

后来找了找资料发现是jquery在ie6下操作select控件有BUG .

$("#hour_").val(2);

改成:

setTimeout(function(){ 
    $("#hour_").val(2); 
},1);

就可以了.

原因是:

Note that the error will only occur if you call appendChild , then
ask for the select 's childNodes , then set the selected property
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.

 

最后可以定义个函数set_select_val来统一设置select控件的值

function set_select_val(sel, val) 

    if($.browser.msie && $.browser.version=="6.0") { 
        setTimeout(function(){ 
            sel.val(val); 
        },1); 
    }else { 
            sel .val(val); 
    } 
}

set_select_val($("#hour"),'2');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息