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

jQuery动态添加元素的AutoComplete仅在首个输入框生效问题求助

解决动态添加输入框无法触发AutoComplete(typeahead)的问题

问题核心是:页面加载时执行的.autocomplete遍历只处理了当时已存在的DOM元素,通过按钮动态添加的新输入框并没有被初始化typeahead插件,所以无法触发自动补全功能。

解决方案

把typeahead的初始化逻辑封装成独立函数,在页面加载时初始化已有元素,每次添加新元素后再对新元素执行初始化:

  1. 封装初始化函数
function initTypeahead($element) {
  $element.typeahead(
    {
      minLength: 1,
      highlight: true,
    },
    {
      name: $element.attr("test-data"),
      source: async (keywords, syncResults, asyncResults) => {
        return $.ajax({
          data: { keywords: keywords },
          dataType: "json",
          success: (response) => {
            return asyncResults(response.items);
          },
          type: "post",
          url: window.URLS["autocomplete"][$element.attr("test-data")],
        });
      },
      limit: 10,
      templates: {
        notFound: "No match",
        pending: "Loading...",
        suggestion: (item) => {
          return `<div>${item}</div>`;
        },
      },
    }
  );
}
  1. 初始化页面加载时已存在的输入框
$(".autocomplete").each((_, item) => {
  initTypeahead($(item));
});
  1. 修改添加按钮事件,初始化新添加的输入框
$data.on("click", ".insert", () => {
  const newContent = document.importNode($data.get(0).querySelector("template").content, true);
  $data.append(newContent);
  // 定位到刚添加的输入框并初始化
  const $newInput = $data.find(".autocomplete").last();
  initTypeahead($newInput);
});

这样修改后,每次新增输入框都会立即绑定typeahead功能,自动补全就能正常触发了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:06:26