當下拉框中的第一項是optGroup時,在用鼠標滾輪改變選項時,如果快速的向上滾動則會把第一項的optGroup選中,這不是我們想要的結果,而且再用代碼獲取下拉框的值是就會發生錯誤。
選中optGroup後,下拉框失去焦點後selectIndex的值在此時還是0(當下拉框中有可選項時).只有在下拉框再次獲得焦點並失去焦點時selectIndex的值才真正的變爲-1,所以簡單的在onblur判斷selectIndex是不行的,所以我們需要作一箇中間的處理,然後判斷selectIndex,如果選中的optGroup則把selectIndex置爲0.
當下拉框只有optGroup時默認是不選中任何項的,也就是空項,空項的selectIndex的也是-1,所以在這種情況下不能直接把selectIndex置爲0(因爲沒有option項),我不能設置爲-1,那樣是沒有任何效果的,我們需要先向下拉框中添加一個option,把selectIndex設爲0,然後再把selectIndex設爲-1,再把新加的option刪除,因爲原則上optGroup是不能選中的,所以把selectIndex設爲-1時選中的將是一個空項。
具體代碼如下:
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<BODY>
<SELECT id="sel" onblur="ValidateElement(this);">
<optgroup label='1111'>
</optgroup>
</SELECT>
<SELECT id="sel1" onblur="ValidateElement(this);">
<optgroup label='1111'>
<option >12</option >
<option >23</option >
<option >34</option >
</optgroup>
<option >aa</option >
<option >bb</option >
<option >cc</option >
</SELECT>
</BODY>
</HTML>
<SCRIPT LANGUAGE="JavaScript">
<!--
function ValidateElement(obj)
{
var t = obj.selectedIndex;
obj.selectedIndex = -1;
obj.selectedIndex = t;
if(obj.selectedIndex == -1)
{
if(obj.options.length > 0)
{
obj.selectedIndex = -1;
obj.selectedIndex = 0;
}
else
{
opt = document.createElement("option");
opt.innerText = "";
obj.insertAdjacentElement("beforeEnd",opt);
obj.selectedIndex = 0;
obj.selectedIndex = -1;
try
{
obj.options[0] = null;
}
catch(e){}
}
}
}
//-->
</SCRIPT>