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

如何为jQuery Autocomplete结果中的不同字段添加类名?

给jQuery Autocomplete的机场名称和国家添加自定义类名

你需要修改_renderItem方法,不再直接使用拼接好的item.label,而是分别将AirportName和Country用带自定义类名的<span>标签包裹,就能单独给它们设置CSS样式了。

修改后的完整代码

<script>
$.ajax({
  url: "airportinfoWeb.xml",
  type: "GET",
  dataType: "xml",
  success: function (xmlResponse) {
    var data = $("Airport", xmlResponse).map(function () {
      return {
        label: $.trim($("AirportName", this).text()) + ", " + $("Country", this).text(),
        AirportCode: $.trim($("AirportCode", this).text()),
        AirportName: $.trim($("AirportName", this).text()),
        Country: $.trim($("Country", this).text())
      };
    }).get();

    $("#id_AirportCode").autocomplete({
      source: function (req, response) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp("^" + re, "i");
        response($.grep(data, function (item) {
          return matcher.test(item.AirportCode) || matcher.test(item.AirportName) || matcher.test(item.Country);
        }));
      },
      position: {
        my: "left+0 top+4"
      }
    }).data("ui-autocomplete")._renderItem = function (ul, item) {
      // 自定义渲染项,分别给机场名称和国家添加类名
      var itemHtml = `<div>
                        <span class="airport-name">${item.AirportName}</span>, 
                        <span class="country">${item.Country}</span>
                      </div>`;
      var $li = $("<li></li>")
        .append(itemHtml)
        .appendTo(ul);
      return $li;
    };
  }
});
</script>

关键修改说明

  • 不再依赖item.label的拼接结果,直接调用数据对象里的item.AirportName和item.Country字段
  • 用<span>分别包裹两个字段,添加airport-name和country类名
  • 原有的搜索匹配逻辑保持不变,仅修改下拉项的渲染结构

示例CSS样式

你可以根据需求编写对应的样式,比如:

.airport-name {
  font-weight: bold;
  color: #2c3e50;
}

.country {
  color: #7f8c8d;
  font-size: 0.9em;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:23:31