开发者

Why does IE not add <option> to my dropDown?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜