基于搜索框内容显示/隐藏结果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(); }); });
关键改动说明
- 给输入值加
trim(),避免用户输入空格时误触发容器显示 - 输入有内容时,先调用
show()显示容器,再加载搜索数据 - 输入为空时,同时执行
empty()和hide(),既清空内容又隐藏容器 - 点击结果项后,额外调用
hide()确保容器及时隐藏
修改后,结果容器只会在输入框有实际文本内容时显示,输入为空(包括清空内容、输入空格)时自动隐藏,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者demo7up
相关产品推荐
相关产品推荐

