IE6 下 jQuery 操作 select的BUG

IE6 下 jQuery 操作 select的BUG

最近在寫一個頁面,在出了ie6外的所有瀏覽器中都正常(ie7,8,9,  firefox, chrome), IE6下提示 “無法設置selected屬性。未指明的錯誤”。

後來發現是jquery 在 ie6 下操作 select控件有BUG.

我程序中是這樣使用的:

$("#genre").val(0);

改成:

setTimeout(function(){ 
    $("#genre").val(0); 
},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); 
    } 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章