Uncaught TypeError: toUpperCase is not a function when binding option dynamically to data-tokens bootstrap

Uncaught TypeError: toUpperCase is not a function when binding option dynamically to data-tokens bootstrap

当我使用 jquery 将数据动态绑定到选项数据令牌时,它抛出 toUpperCase is not a function 错误

当我通过在 HTML 本身中静态传递选项值来尝试 运行 时,它工作正常。但是当动态绑定时它会抛出错误

<div class="col-sm-3">
  <select class="form-control selectpicker" id="select-fund"
                                                    data-live-search="true">
   <!-- <option data-tokens="china">China</option>
   <option data-tokens="malayasia">Malayasia</option>
   <option data-tokens="singapore">Singapore</option> -->
   </select>
   </div>

$(document).ready(function () {
    // $(function () {
    //     $('.selectpicker').selectpicker();
    // });
    // $('.selectpicker').selectpicker();
    temp = { "1": "hello", "2": "world" }
    $.each(temp, function (key, value) {
        $('.selectpicker').append('<option data-tokens= ' + key + '>' + value + '</option>');
    });
    $('.selectpicker').val();
});

添加selectpicker class时默认会初始化selectpicker组件,此时不能添加动态选项,必须先添加选项再初始化组件。

所以删除 class 并使用标识符,例如:

$(document).ready(function() {
  temp = {
    "1": "hello",
    "2": "world"
  }
  $.each(temp, function(key, value) {
    $('#select-fund').append('<option data-tokens= ' + key + '>' + value + '</option>');
  });
  $('#select-fund').selectpicker();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet" />
<div class="col-sm-3">
  <select class="form-control" id="select-fund" data-live-search="true">
  </select>
</div>