jQuery UI Autocomplete获取源函数的输入元素

时间:2017-01-05 14:33:58

标签: jquery-ui jquery-ui-autocomplete

有没有办法在自动完成源函数上获取输入元素? $(this)没有引用自动完成实例的输入。

jsFiddle示例here

<input type="text" data-code="foo" placeholder="type something ..." class="suggest" />
<input type="text" data-code="foo2" placeholder="type something ..." class="suggest" />

JavaScript

$(".suggest").autocomplete({
            delay: 100,
            source: function (request, response) {

                // get foo here,: $(this).data("code"); not working

                // Suggest URL
                var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
                suggestURL = suggestURL.replace('%QUERY', request.term);

                // JSONP Request
                $.ajax({
                    method: 'GET',
                    dataType: 'jsonp',
                    jsonpCallback: 'jsonCallback',
                    url: suggestURL
                })
                .success(function(data){
                    response(data[1]);
                });
            }
        });

1 个答案:

答案 0 :(得分:2)

this.element获取源函数的当前元素。

$(".suggest").autocomplete({
            delay: 100,
            source: function (request, response) {

                this.element.data("code"); 

                // Suggest URL
                var suggestURL = "http://suggestqueries.google.com/complete/search?client=chrome&q=%QUERY";
                suggestURL = suggestURL.replace('%QUERY', request.term);

                // JSONP Request
                $.ajax({
                    method: 'GET',
                    dataType: 'jsonp',
                    jsonpCallback: 'jsonCallback',
                    url: suggestURL
                })
                .success(function(data){
                    response(data[1]);
                });
            }
        });

工作样本here