使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
这在IE8中不起作用(但在FF中起作用):
$("#selectList").append(new Option("option text", "value"));
这确实有效:
var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
其他回答
为了提高性能,您应该尝试只更改DOM一次,如果要添加许多选项,则更应该如此。
var html = '';
for (var i = 0, len = data.length; i < len; ++i) {
html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}
$('#select').append(html);
当您附加选项并使用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
您可以在ES6中执行此操作:
$.each(json, (i, val) => {
$('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
});
如果选项名称或值是动态的,则不必担心其中的特殊字符会被转义;在这种情况下,您可能更喜欢简单的DOM方法:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
这只是最佳性能的快速要点
总是当你处理很多选项时,建立一个大字符串,然后将其添加到“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');