Why does IE not add

2020-05-09 09:10发布

问题:

I'm running this sample script with IE:

var $select = $('#select');
var $button = $('#button');

$button.click(function() {
    var $option = $('<option />');
    $option.text('hello');
    $option.appendTo($select);
});

var $tabs = $('#tabs');
$tabs.tabs();

It's pretty straight forward: when clicking on the button, an option should be added to my dropdown. This works great - the basic fct in IE either.

My problem:
just "open" the dropDown, and "close" it again. Now switch to tab "button" and hit the button. Now switch to tab "select" - a new option should be available.
This works great on every browser except IE ... (sometimes IE messes up after several tab-switches)

How can I fix my script?

回答1:

There's a much simpler, and more cross-browser friendly, way to add options to select boxes than adding option DOM elements (live example):

$button.click(function() {
    var option = new Option('hello');
    $select[0].options.add(option);
});

Perhaps that would work more reliably for you. (Note that it's add, not push. The options object on select elements isn't really an array.)

Instead of options.add you can also do:

$button.click(function() {
    var options = $select[0].options,
        option  = new Option('hello');
    options[options.length] = option;
});

...which also adds to the end, in an array-like way. But add is reliable cross-browser.