简体   繁体   中英

Does IE need an element to be inserted into the DOM before knowing it's properties?


I hope this is not an duplicate question, but a quick search didn't give me any results.
I need to create an <select multiple="multiple"> element dynamically, using data like this:

var _options = [
    {
        MaterialCombined: '123 - asd',
        MaterialName: '123'
    },{
        MaterialCombined: '143123 - asdqw',
        MaterialName: '143123'
    }
];

Now, the following code works perfectly in browsers != IE

var select = new Element('select ', {'multiple ': 'multiple ','size ': ((_options.length > 5) ? 5 : _options.length),'class ': 'AF_ddl ','style ': 'width: 250px'});

for (var i = 0; i < _options.length; ++i) {
    var option = new Element('option ').update(_options[i].MaterialCombined);
    option.value = _options[i].MaterialName;
    select.options.add(option);
}

But in IE, it throws an exception when trying to call add() on the select.options property. Why is that? Does IE need the select to be inserted into the DOM before it can manipulate it?
Note, that I do have it working like this

var tmp = '';
for(var i = 0; i < _options.length; ++i){
    tmp += '<option value="'+_options[i].MaterialName+'">'+_options[i].MaterialCombined+'</option>';
}                                       
var select = new Element('select', {'multiple' : 'multiple', 'size' : ((_options.length > 5) ? 5 : _options.length) , 'class' : 'AF_ddl' , 'style' : 'width:250px'}).update(tmp);

But I really don't like this way of handling my elements: :(

What is the message given by the exception? You could try the alternate method of adding <option> elements to the collection by swapping the line

select.options.add(option);

with

select.options[i] = option;

Edit: or you can use appendChild() :

select.appendChild(option);

Note that IE9 in compat mode was having trouble with the element itself, because of the spaces following the tag name and attribute names in your code. I removed these in the working example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM