如何使用 Javascript/jQuery 设置下拉选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8661287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:57:35  来源:igfitidea点击:

How to set options of a dropdown using Javascript/jQuery?

javascriptjquerydrop-down-menu

提问by Joey Morani

Does anyone know how to set the options and the values of a dropdown menu using javascript or jquery? I'm using this HTML:

有谁知道如何使用 javascript 或 jquery 设置下拉菜单的选项和值?我正在使用这个 HTML:

<select size="1" id="D1">
</select>

Thanks for the help.

谢谢您的帮助。

回答by Purag

You don't even necessarily need jQuery:

你甚至不一定需要 jQuery:

var select = document.getElementById("D1"),
    opt = document.createElement("option");
opt.value = "value";
opt.textContent = "text to be displayed";
select.appendChild(opt);

Example.

例子

But here it is with jQuery anyway:

但无论如何,jQuery 是这样的:

$("select#D1").append( $("<option>")
    .val("value")
    .html("text to be displayed")
);

Example.

例子

回答by Andrew Whitaker

Yet another way of doing it, using select's add method:

另一种方法是使用selectadd 方法

var select = $("#select")[0];

select.add(new Option("one", 1));
select.add(new Option("two", 2));
select.add(new Option("three", 3));

Example:http://jsfiddle.net/pc9Dz/

示例:http : //jsfiddle.net/pc9Dz/

Or another way, by directly assigning values to the select's optionscollection:

或者另一种方式,通过直接为selectoptions集合赋值:

var select = $("#select")[0];

select.options[0] = new Option("one", 1);
select.options[1] = new Option("two", 2);

回答by Michael Stalcup

Here's yet another way to remove options using javascript (similar to Andrew Whitaker's answer) by using the options array:

这是使用选项数组使用 javascript 删除选项的另一种方法(类似于 Andrew Whitaker 的回答):

var select = document.getElementById("D1");
select.options.length = 0;//remove all options

回答by scrappedcola

There are a few different ways. One is:

有几种不同的方法。一种是:

$("#D1").append("<option>Fred</option>");

回答by lubosdz

$("#dropdown").html("<option value='val1'>label 1</option><option value='val2' selected='selected'>label 2</option>");