问题
I need to know what element my select2 UI is based on so that I can grab data from a data-attribute. Maybe I'm missing it in the docs, but I can't seem to figure out how to get it.
Here is the basics of how my code is set up:
<form>
<!--SNIP-->
<select class="select-records" data-index=0>
<option>Choose some records</option>
</select>
<!--SNIP-->
</form>
<script>
$('.select-records').select2({
ajax: {
url: "/ajax/records",
dataType: 'json',
delay: 250,
data: function (params) {
// Need to get the data-index of the base <select> to process/pass along more info here
return {
q: params.term,
page: params.page
}
},
processResults: function(data, page) {
return {
results: data.items
}
},
cache: true
},
minimumInputLength: 3
});
</script>
As you can see, I need to access the data attribute (or id) inside the function that defines the params to sent with the ajax request.
回答1:
Let's say that you want to add to your ajax query ...&ui=select1 for your select element.
Define your select in the following way:
<select data-ajax--id='select1' class="select-records" data-index=0>
Your ajax's data function should now be:
function (params) { return { q: params.term, ui: this.id, page: params.page } }
来源:https://stackoverflow.com/questions/32259070/how-to-get-data-attribute-of-select-for-use-in-select2-from-inside-select2