当下拉框中的第一项是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" οnblur="ValidateElement(this);">
<optgroup label='1111'>
</optgroup>
</SELECT>
<SELECT id="sel1" οnblur="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>