Select2 去除 <option> 中的所有属性

Select2 strips all attributes from <option>

我在我的 select 标签上使用 select2,当用户更改所选选项时会有一些额外的。例如,它使用了我设置为 data-price 的属性。 Select2 似乎从 <option> 标签中剥离除 value 之外的所有属性。

如何禁用此行为或如何以其他方式获取数据值?

编辑:我忘了补充一点,我也在使用 Sonata admin。 Sonata是默认加载select2的那个

Select2 seems to be striping all attributes from the tags except for the value

并非如此,data-* 属性仍然存在,您只需获取它们即可:

$("#singleSelectExample").select2();

$('body').on('change', '#singleSelectExample', function(){
    console.log( $('#singleSelectExample option:selected').data('price') );
})

希望这对您有所帮助。

$("#singleSelectExample").select2();

$('body').on('change', '#singleSelectExample', function(){
  console.log( $('#singleSelectExample option:selected').data('price') );
})
.selectRow {
  display : block;
  padding : 20px;
}
.select2-container {
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/select2/select2-3.5.1/select2.js"></script>
<link href="https://select2.github.io/select2/select2-3.5.1/select2.css" rel="stylesheet"/>
<div class="selectRow">
  <select id="singleSelectExample">
    <option></option>
    <option value="1" data-price="111">Option 1</option>
    <option value="2" data-price="222">Option 2</option>
    <option value="3" data-price="333">Option 3</option>
  </select>
</div>

原来 select2 被设置为使用远程数据,所以我的 option 元素被替换了。我在 AJAX 回调函数中设置了我的数据属性,现在一切正常。