使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
使用jQuery向下拉列表中添加选项的最简单方法是什么?
这行吗?
$("#mySelect").append('<option value=1>My option</option>');
当前回答
这只是最佳性能的快速要点
总是当你处理很多选项时,建立一个大字符串,然后将其添加到“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');
其他回答
如果选项名称或值是动态的,则不必担心其中的特殊字符会被转义;在这种情况下,您可能更喜欢简单的DOM方法:
var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
您可以尝试以下代码附加到选项
<select id="mySelect"></select>
<script>
$("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
</script>
$(function () {
var option = $("<option></option>");
option.text("Display text");
option.val("1");
$("#Select1").append(option);
});
如果您从某个对象获取数据,那么只需将该对象转发到函数。。。
$(function (product) {
var option = $("<option></option>");
option.text(product.Name);
option.val(product.Id);
$("#Select1").append(option);
});
名称和Id是对象财产的名称。。。所以你可以随便叫他们。。。当然,如果您有Array。。。你想用for循环构建自定义函数。。。然后调用文档就绪中的函数。。。干杯
如果您在select中有optgroup,则在DOM中出现错误。
我认为最好的方法是:
$("#select option:last").after($('<option value="1">my option</option>'));
您可以使用以下语法添加选项,也可以访问jQuery中的way handle选项以了解更多详细信息。
$('#select').append($('<option>',{value:1,text:'One'}));$('#select').append('<option value=“1”>一个</option>');var option=新选项(文本,值)$('#select').append($(选项));