2

我正在使用 JQuery UI 的自动完成小部件,并希望能够访问我将自动完成附加到的当前选择器。我找到了一种访问选择器的方法,在这里使用前面的问题,但是源函数被错误地调用。

我当前的代码看起来像这样

$("input[id$=artist]").each(function() {
    e1 = $(this);
    curID = $(this).parent('td').parent('tr').attr('id');       
    e1.autocomplete({
        minLength: 3,
        source: function(request, response) { 
            findSuggestions(request, response, 'artist', artist_cache, curID);
        }
    });
});

如您所见,我得到了当前选择器并将其放入 e1 中。给定的“艺术家”输入有多行,我希望能够知道方法中每一行的 ID,findSuggestions但是当调用该方法时,每一行都被赋予相同的 ID(这是引用最后一个行。

知道为什么会发生这种情况吗?我是否错误地处理了这个问题?

谢谢!

4

2 回答 2

3

您需要在闭包内定义变量以赋予其局部范围,否则您将创建一个全局变量

$("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);
        }
    });
});
于 2010-07-15T07:59:26.740 回答
2

你忘了把变量放在var前面。curID

这会在窗口对象上创建一个全局变量curID,因此每个源回调函数都引用同一个对象,因此是值。

改成

var curID = $(this).parent('td').parent('tr').attr('id');       

永远不要忘记var在变量声明之前放置,因为它可能是诸如此类的痛苦错误的根源。

于 2010-07-15T08:00:17.503 回答