You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery Autocomplete中判断当前Input元素,复用自动补全代码

问题:复用自动补全代码时识别当前聚焦的Input元素

我有多个外观相似的input元素,仅输入的供应商代码类型不同(酒店供应商代码或租车供应商代码)。为避免重复编写自动补全JavaScript代码,希望复用同一套代码,但需要识别当前聚焦的input元素,以返回正确的代码。我尝试判断当前关联事件的input DOM元素是“vendor-car”还是“vendor-hotel”,但$(this).attr("id")返回undefined,无法获取当前元素。

HTML代码

<label>Hotel Vendor Codes</label>
<input type="text" class="form-control vendor-autocomplete vendor-hotel" id="Vendor_hotel" />

<label>Car Vendor Codes</label>
<input type="text" class="form-control vendor-autocomplete vendor-car" id="Vendor_car" />

原TypeScript代码

var vendorAutocompletes = $('.vendor-autocomplete');
var vendorCar = $('.vendor-car');

if (vendorAutocompletes.length > 0) {
    vendorAutocompletes
        .autocomplete({
            source: function (request, response) {

                if ($(this).attr("id") == vendorCar.attr("id")) {
                    console.log('This input is Car Vendors');
                    getVendors(request.term, VendorTypes.Car, response);
                } else {
                    console.log('This input is Hotel Vendors');
                    getVendors(request.term, VendorTypes.Hotel, response);
                }
            }

        });
}

解决方案

问题出在jQuery UI Autocomplete的source回调上下文:这里的this指向的是Autocomplete插件的实例对象,而非当前触发的input元素,所以直接用$(this)无法获取input的属性。下面是两种可行的解决方式:

方式一:通过插件实例的element属性获取当前input

修改source回调里的判断逻辑,利用插件实例的element属性拿到绑定的input元素:

var vendorAutocompletes = $('.vendor-autocomplete');

if (vendorAutocompletes.length > 0) {
    vendorAutocompletes
        .autocomplete({
            source: function (request, response) {
                const $currentInput = $(this.element);
                if ($currentInput.hasClass('vendor-car')) {
                    console.log('This input is Car Vendors');
                    getVendors(request.term, VendorTypes.Car, response);
                } else {
                    console.log('This input is Hotel Vendors');
                    getVendors(request.term, VendorTypes.Hotel, response);
                }
            }
        });
}

这种方式直接通过插件实例获取当前input,再用hasClass判断类型,比判断ID更灵活,就算后续ID变更也不影响逻辑。

方式二:遍历元素时提前确定类型

初始化插件时遍历每个input,提前确定对应的供应商类型,回调里直接使用预定义的变量:

var vendorAutocompletes = $('.vendor-autocomplete');

if (vendorAutocompletes.length > 0) {
    vendorAutocompletes.each(function() {
        const $input = $(this);
        const vendorType = $input.hasClass('vendor-car') ? VendorTypes.Car : VendorTypes.Hotel;
        
        $input.autocomplete({
            source: function (request, response) {
                getVendors(request.term, vendorType, response);
            }
        });
    });
}

这种方式把类型判断提前到初始化阶段,回调逻辑更简洁,也避免了每次触发自动补全都重复判断元素类型。

内容的提问来源于stack exchange,提问作者Dustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 06:25:23