Javascript JQuery 创建新的选择选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2767587/
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-23 01:50:52  来源:igfitidea点击:

JQuery create new select option

javascriptjqueryhtmljquery-selectors

提问by van

I have the below functions in regular JavaScript creating select options. Is there a way I can do this with jQuery without having to use the form object? Perhaps storing the options as an array of JSON objects and parsing this in the calling function...

我在常规 JavaScript 创建选择选项中有以下功能。有没有一种方法可以用 jQuery 做到这一点而不必使用表单对象?也许将选项存储为 JSON 对象数组并在调用函数中解析它......

function populate(form)
{
form.options.length = 0;
form.options[0] = new Option("Select a city / town in Sweden","");
form.options[1] = new Option("Melbourne","Melbourne");
}

Below is how I call the function above:

下面是我如何调用上面的函数:

populate(document.form.county); //county is the id of the dropdownlist to populate.    

回答by Harold1983-

Something like:

就像是:

function populate(selector) {
  $(selector)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

populate('#myform .myselect');

Or even:

甚至:

$.fn.populate = function() {
  $(this)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

$('#myform .myselect').populate();

回答by Tejs

What about

关于什么

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

回答by CaffGeek

How about

怎么样

$('#county').append(
    $('<option />')
        .text('Select a city / town in Sweden')
        .val(''),
    $('<option />')
        .text('Melbourne')
        .val('Melbourne')
);

回答by mdBender

If you need to make single element you can use this construction:

如果您需要制作单个元素,您可以使用以下结构:

$('<option/>', {
    'class': this.dataID,
    'text': this.s_dataValue
}).appendTo('.subCategory');

But if you need to print many elements you can use this construction:

但是如果你需要打印很多元素,你可以使用这种结构:

function printOptions(arr){
    jQuery.each(arr, function(){
        $('<option/>', {
            'value': this.dataID,
            'text': this.s_dataValue
        }).appendTo('.subCategory');
    });
}

回答by Tim Down

This is confusing. When you say "form object", do you mean "<select>element"? If not, your code won't work, so I'll assume your formvariable is in fact a reference to a <select>element. Why do you want to rewrite this code? What you have has worked in all scriptable browsers since around 1996, and won't stop working any time soon. Doing it with jQuery will immediately make your code slower, more error-prone and less compatible across browsers.

这令人困惑。当您说“表单对象”时,您指的是“<select>元素”吗?如果没有,您的代码将无法工作,因此我假设您的form变量实际上是对<select>元素的引用。为什么要重写这段代码?自 1996 年左右以来,您在所有可编写脚本的浏览器中所做的工作都不会很快停止工作。使用 jQuery 执行此操作将立即使您的代码更慢、更容易出错并且跨浏览器的兼容性更低。

Here's a function that uses your current code as a starting point and populates a <select>element from an object:

这是一个使用当前代码作为起点并<select>从对象填充元素的函数:

<select id="mySelect"></select>

<script type="text/javascript>

function populateSelect(select, optionsData) {
    var options = select.options, o, selected;
    options.length = 0;
    for (var i = 0, len = optionsData.length; i < len; ++i) {
        o = optionsData[i];
        selected = !!o.selected;
        options[i] = new Option(o.text, o.value, selected, selected);
    }
}

var optionsData = [
    {
        text: "Select a city / town in Sweden",
        value: ""
    },
    {
        text: "Melbourne",
        value: "Melbourne",
        selected: true
    }
];

populateSelect(document.getElementById("mySelect"), optionsData);

</script>

回答by Tony Norcross

A really simple way to do this...

一个非常简单的方法来做到这一点......

// create the option
var opt = $("<option>").val("myvalue").text("my text");

//append option to the select element
$(#my-select).append(opt);

This could be done in lots of ways, even in a single line if really you want to.

这可以通过多种方式完成,如果您真的愿意,甚至可以在一行中完成。