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

点击下拉列表后如何为自动补全搜索的目标输入框添加焦点

问题:自动补全下拉项选中后为输入框添加焦点

我正在实现自动补全搜索功能,输入框代码如下:

<input autofocus type="text" id="country_name" name="d1"  autocomplete="off" required size="5" tabIndex="1">

关联的资源文件:

<link href="library/bootstrap-5/bootstrap.min.css" rel="stylesheet" />
<script src="library/bootstrap-5/bootstrap.bundle.min.js"></script>
<script src="library/autocomplete.js"></script>

在autocomplete.js的下拉项点击事件处理代码中,设置选中项的值后,希望为输入框添加焦点,当前代码如下:

this.field.nextSibling.querySelectorAll('.dropdown-item').forEach((item) => {
          item.addEventListener('click', (e) => {
            let dataLabel = e.target.getAttribute('data-label');
            let dataValue = e.target.getAttribute('data-value');
    
            this.field.value = dataLabel;
    
            if (this.options.onSelectItem) {
              this.options.onSelectItem({
                value: dataValue,
                label: dataLabel
              });
            }
            
            //add focus on the inputbox
         
            this.dropdown.hide();
          })
解决方案

直接调用输入框的focus()方法即可,考虑到Bootstrap下拉菜单隐藏涉及DOM操作,建议在this.dropdown.hide()之后执行,确保下拉菜单完全隐藏后再给输入框焦点:

修改后的代码如下:

this.field.nextSibling.querySelectorAll('.dropdown-item').forEach((item) => {
          item.addEventListener('click', (e) => {
            let dataLabel = e.target.getAttribute('data-label');
            let dataValue = e.target.getAttribute('data-value');
    
            this.field.value = dataLabel;
    
            if (this.options.onSelectItem) {
              this.options.onSelectItem({
                value: dataValue,
                label: dataLabel
              });
            }
            
            //add focus on the inputbox
            this.dropdown.hide();
            // 为输入框添加焦点
            this.field.focus();
          })

如果执行后焦点仍未生效,可尝试用setTimeout延迟执行,确保DOM操作完成:

// 替换上面的focus代码
setTimeout(() => {
  this.field.focus();
}, 100);

内容的提问来源于stack exchange,提问作者JIA WEI LEONG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 10:32:09