问题
I've got a behaviour a bit strange with Select Box and OptGroup:
I use OptGroup and try to add at the end a single item which I expect to be out of the OptGroup. FF does it as expected but IE adds it to the OptGroup
With this code : fiddle (Note: JQuery was just use for the .ready method, I can't use it in my project)
<select id="selectbox">
<optgroup label="optGroup1">
<option>aaaa</option>
</optgroup>
</select>
$(document).ready(function() {
var select = document.getElementById("selectbox");
option = document.createElement( 'option' );
option.value = option.text = "test";
select.add( option );
});
The result is different in IE and FF
IE:
FF:
Note : I'm using Javascript to add the item because I'm currently using GWT. So this is the way GWT adds an item to a select.
回答1:
This works in IE and Chrome, so it should work in FF:
$(document).ready(function() {
var select = document.getElementById("selectbox");
option = document.createElement( 'option' );
option.value = option.text = "test";
select.appendChild( option );
});
回答2:
You can actually insert the option after option group:
HTML (added ID for the Option Group)
<select id="selectbox">
<optgroup label="optGroup1" id="optGroup1">
<option>aaaa</option>
</optgroup>
</select>
JavaScript
var optgroup1 = document.getElementById("optGroup1");
option = document.createElement( 'option' );
option.value = option.text = "test";
//insterting "after"
optgroup1.parentNode.insertBefore(option, optgroup1.nextSibling)
Demo: http://jsfiddle.net/tZ8sz/1/
来源:https://stackoverflow.com/questions/22221289/select-box-on-ie-item-is-added-to-optgroup-instead-of-root-ff-ok