如何将选项附加到选择

时间:2016-11-07 16:34:41

标签: javascript jquery css

我有一个包含数字的变量。我想根据变量编号附加一个带有数值的选项(即:如果总数等于10,那么我需要在select中添加10个选项,每个选项包含下一个数字行值,所以1,2,3,4 ......等等。我从一个硬编码选项开始,然后我需要动态地为每个案例添加选项。我已经尝试了大量的脚本,但我"得到"不能在运营商中搜索长度。

https://jsfiddle.net/v1yyhfm8/

HTML

 <select id="main">
     <option selected>1</option>
 </select>

我试过了:

 var total = dataSource.total();
 for (var i = 1; 1 <= total; i++) {
     var added = document.createElement('option');
     var test = $('#main');
     added.value = i;
     added.innerHTML = i;
     test.append(added);
 }

  var total = dataSource.total();
  $.each(total, function (i, item) {
    $('#main').append($('<option>', {
       value: item.total,
       text: item.text
    }));                               
  });

2 个答案:

答案 0 :(得分:1)

在你的代码中,for循环条件总是为true,导致无限循环,因此将其更改为i <= total

var total = dataSource.total();
for (var i = 1; i <= total; i++) {
    var added = document.createElement('option');
    var select1 = $('#main');
    added.value = i;
    added.innerHTML = i;
    select1.append(added);
}

var total = 10;
for (var i = 1; i <= total; i++) {
  var added = document.createElement('option');
  var select1 = $('#main');
  added.value = i;
  added.innerHTML = i;
  select1.append(added);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="main">
  <option selected>1</option>
</select>

答案 1 :(得分:0)

Html part :
 <select id="main">

 </select>

 Jquery Part:


  var opt = ' <option selected>1</option>';
  for(var i = 2; i<= 10; i++){
    opt += ' <option>' + i + '</option>';

  }
  $("#main").append(opt);

Jsfiddle链接:https://jsfiddle.net/v1yyhfm8/