如何从Select2中的数据源设置data- *? [英] How to set data-* from datasources in Select2?
问题描述
我使用Select2如下:
I am using Select2 as follow:
$('select#fields').select2({
placeholder: 'Select a field',
data: data.fields
});
data.fields
是这样的JSON一个:
data.fields
is a JSON like this one:
"fields": [
{
"id": "companies_id",
"text": "companies_id",
"data-type": "int"
},
{
"id": "parent_companies_id",
"text": "parent_companies_id",
"data-type": "int"
},
{
"id": "client_of_companies_id",
"text": "client_of_companies_id",
"data-type": "int"
},
{
"id": "asset_locations_id",
"text": "asset_locations_id",
"data-type": "int"
},
{
"id": "companies_name",
"text": "companies_name",
"data-type": "varchar"
},
{
"id": "companies_number",
"text": "companies_number",
"data-type": "varchar"
}
]
id
和 text
用于填充选项值,我可以使用第三个值 data-type
并将其设置为< option>
的属性?如果是这样的话?可以给我一个例子吗?
id
and text
are used to fill the option values, can I use the third value data-type
and set it as an attribute for the <option>
? If so how? Can any leave me an example?
推荐答案
实际上 - 默认情况下select2会保存中的所有属性数据('data')
它创建的< option>
元素的变量,您始终可以使用<$ c访问这些值$ c> $(< option>)。data('data'),但要记住它不是与 .data相同('type')
for data-type =value
。您需要使用属性的完整名称。
Actually - select2 by default saves all of the attributes in the data('data')
variable of the <option>
element that it creates, and you can always access these values using the $(<option>).data('data')
, however keep in mind that it's not the same as .data('type')
for data-type="value"
. You need to use the complete name of the attribute.
以下是如何获取 data-type $ c的值的示例$ c> on
select
event:
Here is an example of how to get the value of data-type
on select
event:
var $example = $("#s1").select2({
data: [
{
"id": "companies_id",
"text": "companies_id",
"data-type": "int",
"data-extra": '1'
},
{
"id": "parent_companies_id",
"text": "parent_companies_id",
"data-type": "int",
"data-extra": '2'
},
{
"id": "client_of_companies_id",
"text": "client_of_companies_id",
"data-type": "int",
"data-extra": '3'
},
{
"id": "asset_locations_id",
"text": "asset_locations_id",
"data-type": "int",
"data-extra": '4'
},
{
"id": "companies_name",
"text": "companies_name",
"data-type": "varchar",
"data-extra": '5'
},
{
"id": "companies_number",
"text": "companies_number",
"data-type": "varchar",
"data-extra": '6'
}
],
}).on('select2:select', function(e) {
console.log(e.params.data['data-type'], e.params.data['data-extra']);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>
<select id="s1">
</select>
这篇关于如何从Select2中的数据源设置data- *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!