简体   繁体   English

如何使$(this)在JQueryUI自动完成中工作

[英]How to get the $(this) to work in JQueryUI autocomplete

Here is a fiddle example 这是一个小提琴的例子

I have trouble getting the $(this) to work in the source function with jQueryUI autocomplete. 我很难让$(this)在jQueryUI自动完成功能的源函数中工作。 The console shows that the search input isn't able to get its data attribute 'name' before sending out an Ajax request. 控制台显示,在发出Ajax请求之前,搜索输入无法获取其数据属性“名称”。 Is there any way to pass the variable "name" to data ? 有什么办法可以将变量“名称”传递给data

$('.input').autocomplete({
    source: function (request, response) {
        var name = $(this).data('name');
        console.log(name);
        $.ajax({
            url: url,
            dataType: "json",
            data: {
                'q': request.term,
                'field': name
            },
            success: function (data) {
                response($.map(data.query.results.json.json, function (item) {
                    return {
                        label: item.name,
                    }
                }));
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        $(this).val(ui.item.label);
        $(this).val(ui.item.label);
    },
    open: function () {
        $(this).autocomplete("widget").width(400)
    }
});

You should use this.element to access corresponding input element. 您应该使用this.element访问相应的输入元素。 this points to the autocomplete instance itself: this指向自动完成实例本身:

var name = $(this.element).data('name');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM