如何获取select2中所选选项的data- *值?
这就像本主题的第二部分,现在我需要能够从一个选择到另一个选择读取动态data-*
属性。 这是什么意思?
首先看一下下图:
你看到的是以下代码的作用:
// This turn 1st and 3rd into select2 $('#module, #conditions').select2(); // This turn 2nd into select2 using data from a datasource $('select#fields').select2({ placeholder: 'Select a field', data: data.fields });
正如我在引用的主题中发布的那样, data.fields
有一个类似于以下内容的JSON:
"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" } ]
在这种情况下,我需要从第三个选择(条件)上的onChange()
事件中读取分配给第二个select(字段)的data-*
属性,然后对INPUT进行一些修改(但这是在我身上)。
如何从任何其他select2元素中获取data-*
值?
问题更多的是“如何在select2中获取所选选项的data-*
值?”。
检查此示例:
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']); }); $('button').click(function() { option_el = $('#s1 :selected'); data = option_el.data('data') console.log(data['data-type']) console.log(data['data-extra']) });