我在我的select
標記上使用select2,當用戶更改所選選項時還有一些額外的屬性。並且它使用了我設置爲data-price
的屬性。除了value
之外,Select2似乎正在剝離<option>
標記中的所有屬性。Select2剝離所有屬性<option>
如何禁用此行爲或如何以其他方式獲取數據值?
編輯:我忘了補充說我也在使用索納塔管理員。 Sonata默認是加載select2的一個。
我在我的select
標記上使用select2,當用戶更改所選選項時還有一些額外的屬性。並且它使用了我設置爲data-price
的屬性。除了value
之外,Select2似乎正在剝離<option>
標記中的所有屬性。Select2剝離所有屬性<option>
如何禁用此行爲或如何以其他方式獲取數據值?
編輯:我忘了補充說我也在使用索納塔管理員。 Sonata默認是加載select2的一個。
原來選擇2設置,所以我option
元素被替換使用遠程數據。我在AJAX回調函數中設置了我的數據屬性,現在一切正常。
選擇二似乎是條帶化從標籤的所有屬性,除了價值
不是真的在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>
在您的示例中,數據屬性保存在HTML中。這不會發生在我的情況。也許別的東西是原因,而不是select2,但你的例子工作正常,而我的沒有。 – ecc
我忘了補充說我還在使用Sonata ... – ecc