使用jQuery向下拉列表中添加选项的最简单方法是什么?

这行吗?

$("#mySelect").append('<option value=1>My option</option>');

当前回答

当您附加选项并使用jqueryvalidate时,我们发现了一些问题。您必须在选择多个列表中单击一个项目。您将添加此代码以处理:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

其他回答

这很好。

如果添加多个选项元素,我建议执行一次追加,而不是对每个元素执行追加。

您可以将选项动态添加到下拉列表中,如下图所示。在此示例中,我获取了数组数据,并将这些数组值绑定到下拉列表中,如输出截图所示

输出:

var resultData=[“孟买”,“德里”,“钦奈”,“果阿”]$(文档).ready(函数){var myselect=$('<select>');$.each(resultData,函数(索引,键){myselect.append($('<option></option>').val(key).html(key));});$(“#selectCity”).append(myselect.html());});<script src=“https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script><select id=“selectCity”></选择>

Try

mySelect.innerHTML+= '<option value=1>My option</option>';

btn.onclick=_=>mySelect.innerHTML+=`<optionselected>${+newDate}</option>`<button id=“btn”>添加选项</button><select id=“mySelect”></select>

可以使用文本附加和设置“值”属性:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));

这只是最佳性能的快速要点

总是当你处理很多选项时,建立一个大字符串,然后将其添加到“select”中以获得最佳性能

f.g.

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

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// 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');

甚至更快

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');