问题
I have create javascript like this
$(document).on("select2:open", ".provider_suggestion", function() {
$(this).select2({
minimumInputLength: 2,
ajax: {
url: "../include/suggestion/provider_name.php",
dataType: 'json',
delay: 250,
data: function(params){ return { q: params.term }; },
processResults: function (data, page) { return { results: data }; },
cache: true
}
});
});
and create select html input like this
<select id="c_providers" name="c_providers" class="provider_suggestion" style="width:100%"></select>
and when page loaded, I click the select input.
I open the browser console, its mentioned that
Uncaught TypeError: Cannot read property 'query' of null
I still dont understand about this issue.
回答1:
You must have already initialized the select2 somewhere previous to your provided code snippet, or I expect the select2:open
listener would never fire and cause your problem. When I replicated the situation in a fiddle and peeked at the select2 source, it seemed that select2 was complaining about a dataAdapter
being null, which must be a side effect of this double select2() call, or that the .select2() call is inside the listener with an unexpected context... Or something, don't have the time or interest to explore down to the root cause.
Regardless, moving the .select2() call out of the listener (and removing the then empty listener) removed the problem. Based on the limited information available in your question, it does not seem like there is any need at all to use this listener, at least the way you are using it. A simplistic working example is in this JSfiddle, where the only real difference to your original code is the removal of the listener wrapping (and the mocking of AJAX calls). So, try something like
$('#c_providers').select2({
minimumInputLength: 2,
ajax: {
url: "../include/suggestion/provider_name.php",
dataType: 'json',
delay: 250,
data: function(params){ return { q: params.term }; },
processResults: function (data, page) { return { results: data }; },
cache: true
}
});
as the only select2 initialization for this #c_providers
element.
来源:https://stackoverflow.com/questions/37016655/select2-cannot-read-property-query-of-null