简体   繁体   English

Bootstrap select2 不适用于 js 功能

[英]Bootstrap select2 not working with js function

I have the following code:我有以下代码:

In htmlhtml 中

<select multiple id="e1" style="width:200px"></select>

In js I have a function to fill the options.js 中,我有一个函数来填充选项。

$('#e1').select2();
   for (var i in this.notSelected) {
     var options = '<option data-idx="'+ i +'">' + this.notSelected[i][field] + '</option>';
     $('#e1').append(options);
   }

If I click in the editText I can see the options but I can't select anything.如果我单击 editText 我可以看到选项但我不能选择任何内容。

Any examples or help about this?任何例子或帮助?

Thanks.谢谢。

You should use for loop like this.你应该像这样使用 for 循环。 It is not good approach to access DOM so many time.多次访问 DOM 并不是一个好方法。 So do this after for loop.所以在 for 循环之后执行此操作。

  var options = '';
  for (var i=0;i<this.notSelected.length;i++) {
      var temp = this.notSelected[i];
      var options += '<option value="'+ temp +'">' + temp[field] +'</option>';
  }
  $('#e1').append(options);

Below is the running code.下面是运行代码。

 $(document).ready(function(){ $('#e1').select2(); var ad = ['Op1', 'Op2', 'Op3']; var op = ''; for (var i=0; i<ad.length;i++){ op += '<option data-idx="'+i+'">'+ad[i]+'</option>'; } $('#e1').append(op); });
 <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1-rc.1/css/select2.min.css" rel="stylesheet" /> <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1-rc.1/js/select2.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <select multiple id='e1' style="width: 400px;"> </select> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM