【问题标题】:How to update <select> options in my case?在我的情况下如何更新 <select> 选项?
【发布时间】:2011-08-09 13:01:30
【问题描述】:

我有一个选择字段和一个按钮:

<select id="mylist"></select>
<input type="button" id="btn" value="update">

我的js代码:

var btn=$('#btn');
btn.click(function(){
   var optionList = GET_LIST();// GET_LIST() returns a array of strings which is the option texts.

   //How to use optionList to update the options in <select> ?
});

如何在选择标签中使用optionList 更新我的选项列表?

【问题讨论】:

  • 它返回一个字符串数组,即选项文本
  • “更新”选项是什么意思?您想如何更新它们?
  • @Ryan,表示

标签: javascript jquery jquery-ui jquery-selectors jquery-events


【解决方案1】:

编辑:基于@amsutil 使用 html 替代的注释:

var btn=$('#btn');
btn.click(function(){
     var optionList = GET_LIST();
     var select  = $("#mylist");
     select.html("");
     var optionsHTML = "";
     $.each(optionList, function(a, b){
        optionsHTML += "<option>" + b + "</option>";
     });
     select.html(optionsHTML);
});

试试这个:

var btn=$('#btn');
btn.click(function(){
     var optionList = GET_LIST();
     var select  = $("#mylist");
      select.empty();
     $.each(optionList, function(a, b){
        select.append("<option>" + b + "</option>");
     });
});

【讨论】:

  • 如果您要多次按下此按钮,您可能希望先从选择中删除子项(选项)?
  • @Chris:更新帖子以处理您提到的问题。
  • 我不会使用追加。一方面,它创建了太多的 DOM 操作(想象一下,如果你在这个数组中有 200 个元素,比如一个国家列表),而且你每次都必须继续清空它。如果将所有新选项存储为字符串,并使用 .html() 将其添加到选择中,则这两个问题都将被根除。
  • 但是如果有新的更新,这将保留之前的选项列表...如何删除之前的选项列表?
【解决方案2】:

如果您想从数组中创建选择选项,您的值和标签文本将匹配。如果您希望值和文本不同,则需要将它们存储在对象中:

var btn = $('#btn');

btn.click(function() {
    var optionList = GET_LIST();
    var element = $('#mylist');

    $.each(optionList, function(index, value) {
       element.append('<option value="' + value + '">' + value + '</option>');
    });
});

【讨论】:

  • 但是如果有新的更新,这将保留之前的选项列表...如何删除之前的选项列表?
【解决方案3】:

我看到一些使用“附加”的答案,但这会产生太多的 DOM 操作。如果您的数组中有大量值,则可能会降低站点速度。最好将所有新选项存储在一个字符串中,并在最后进行一次 DOM 操作。

演示:http://jsbin.com/ubotu4/

【讨论】:

    【解决方案4】:

    使用$.map() 将字符串数组转换为选项元素数组:

    var optionList = GET_LIST();
    var options = $.map(optionList, function (item, i) {
        return $('<option>', {text: item});   // Convert string into <option>
    });
    $('#mylist').empty().append(options);     // Append to the <select>
    

    【讨论】:

      猜你喜欢
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2016-03-23
      • 1970-01-01
      相关资源
      最近更新 更多