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

基于搜索框内容显示/隐藏结果DIV的实现问题

解决搜索结果DIV仅在输入框有内容时显示/隐藏的问题

直接修改JS逻辑,根据输入框内容的有无精准控制结果容器的显示状态,就能实现需求:

修改后的JS代码

$(document).ready(function () {
  // 初始化隐藏结果容器
  const resultEl = document.getElementById('result');
  resultEl.style.display = 'none';

  $('.search-box input[type="text"]').on('keyup input', function () {
    const inputVal = $(this).val().trim(); // 过滤空格,避免误触发
    const resultDropdown = $(this).siblings('.result');

    if (inputVal.length > 0) {
      // 有实际内容时,显示容器并加载搜索结果
      resultDropdown.show();
      $.get('php/jira-search.php', { term: inputVal }).done(function (data) {
        resultDropdown.html(data);
      });
    } else {
      // 无内容时,清空容器内容并隐藏
      resultDropdown.empty().hide();
    }
  });

  // 点击结果项填充输入框后,隐藏结果容器
  $(document).on('click', '.result p', function () {
    $(this)
      .parents('.search-box')
      .find('input[type="text"]')
      .val($(this).text());
    $(this).parent('.result').empty().hide();
  });
});

关键改动说明

  1. 给输入值加trim(),避免用户输入空格时误触发容器显示
  2. 输入有内容时,先调用show()显示容器,再加载搜索数据
  3. 输入为空时,同时执行empty()和hide(),既清空内容又隐藏容器
  4. 点击结果项后,额外调用hide()确保容器及时隐藏

修改后,结果容器只会在输入框有实际文本内容时显示,输入为空(包括清空内容、输入空格)时自动隐藏,完全匹配你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:00:46