【问题标题】:How to get selected attribute from dropdown using JQuery select2()?如何使用 JQuery select2() 从下拉列表中获取选定的属性?
【发布时间】:2014-01-17 12:48:32
【问题描述】:

我正在使用此方法将值和文本添加到选项中,但我还需要添加 selected 属性。我怎样才能做到这一点?这是我的方法……:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
        // is it possible to add here something like this: select: "selected"
    }));
});

【问题讨论】:

标签: select append option


【解决方案1】:

你可以直接构建一个字符串并将其传递给 append 函数

$.each(items, function(i, item) {
    // do some kind of check here if value matches foo
    var selected = item.value == foo ? 'selected="selected"' : '';

    var opt = '<option value="' + item.value + '" ' + selected + '>';
    opt += item.text + '</option>';

    // append string directly
    $('#mySelect').append(opt);
});

【讨论】:

    【解决方案2】:

    $('select').select2(); // 只需添加这行代码,它会将您的下拉菜单设置为默认值

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2021-05-23
      相关资源
      最近更新 更多