select2 下拉列表中的换行符

Line break in select2 dropdown

您好,我正在使用 select2 下拉菜单

代码类似于下面

<select class="js-example-basic-single id='select2'>
<option value="10">this is a option x <br>value is 10</option>
<option value="20">this is option y<br> value is 20</option>
</select>

<script>
$(document).ready(function() {
    $('.js-example-basic-single').select2();
});
<script>

这种换行方式不起作用,我该如何让它起作用或者我还能用什么来换行?

如果您在选项的文本中放置了一个可识别的占位符,您可以搜索它并在 select2 插件中放置一个换行符。为此,您可以简单地使用 select2.

template functions

但您一定不要忘记,例如屏幕阅读器或 google 搜索引擎只会看到您的占位符,不一定会看到被替换的文本。所以请谨慎选择占位符。

$(document).ready(function() {

  function templateResult(item, container) {
    // replace the placeholder with the break-tag and put it into an jquery object
    return $('<span>' + item.text.replace('[br]', '<br/>') + '</span>');
  }

  function templateSelection(item, container) {
    // replace your placeholder with nothing, so your select shows the whole option text
    return item.text.replace('[br]', '');
  }

  $('.js-example-basic-single').select2({
    templateResult: templateResult,
    templateSelection: templateSelection
  });

});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

<select class="js-example-basic-single" id="select2">
  <option value="10">this is a option x [br]value is 10</option>
  <option value="20">this is option y[br] value is 20</option>
</select>