Adding options to a <select> using jQuery?

后端 未结 30 1641
萌比男神i
萌比男神i 2020-11-22 03:56

What\'s the easiest way to add an option to a dropdown using jQuery?

Will this work?

$(\"#mySelect\").append(\'
30条回答
  •  隐瞒了意图╮
    2020-11-22 04:38

    This is just a quick points for best performance

    always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

    f.g.

    var $mySelect = $('#mySelect'); var str = '';

    $.each(items, function (i, item) {
        // IMPORTANT: no selectors inside the loop (for the best performance)
        str += "";
    });
    // you built a big string
    
    $mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
    $mySelect.multiSelect('refresh');
    

    Even faster

    var str = ""; 
    for(var i; i = 0; i < arr.length; i++){
        str += "";
    }    
    $mySelect.html(str);
    $mySelect.multiSelect('refresh');
    

提交回复
热议问题