Using current selector in JQuery autocomplete
I'm using JQuery UI's autocomplete widget and would like to have access to the current selector which I'm attaching the autocomplete to. I have found a way to access the selector, using a previous question here, but the source function is called with incorrectly.
My current code looks like this
$("input[id$=artist]").each(function() {
e1 = $(this);
curID = $(this).parent('td').parent('tr').attr('id');
e1.autocomplete({
minLength: 3,
source: function(request, res开发者_如何学Cponse) {
findSuggestions(request, response, 'artist', artist_cache, curID);
}
});
});
As you can see, I get the current selector and put it into e1. There are multiple rows with the given 'artist' input and I want to be able to know the ID for each row in the findSuggestions
method but when the method is called, each row is given the same ID (which is the referencing the last of the rows.
Any idea why this might be occurring? Am I approaching this problem incorrectly?
Thanks!
You need to define your variable inside the closure to give it local scope otherwise you are creating a global variable
$("input[id$=artist]").each(function() {
var e1 = $(this);
var curID = $(this).parent('td').parent('tr').attr('id');
e1.autocomplete({
minLength: 3,
source: function(request, response) {
findSuggestions(request, response, 'artist', artist_cache, curID);
}
});
});
You forgot to put var
before the curID
variable.
That creates a global variable curID
on the window object, so every source callback function is referring to the same object, and thus value.
Change to
var curID = $(this).parent('td').parent('tr').attr('id');
Never forget to put var
before a variable declaration, as it can be the source of painful bugs such as this one.
精彩评论