当用户点击搜索结果中的标题时,Focusout功能可防止用户重定向到标题页.每当我点击页面上的不同元素时,它就会按预期关闭搜索结果,但每当我点击搜索结果时,搜索结果也会关闭.

我try 使用blur函数以及Hide()和show(),但得到了相同的结果.我知道我有.Result Display None,但这不应该阻止我点击搜索结果?这是怎么回事?

// jquery.js

$(document).ready(function() {
  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      $.get("includes/searchbar.inc.php", {
        term: inputVal
      }).done(function(data) {
        // Display the returned data in browser
        resultDropdown.html(data);
        $('.result').css('display', 'block');

        $("#searchboxy").focusout(function() {
          $('.result').css('display', 'none');
        });
        $("#searchboxy").focusin(function() {
          $('.result').css('display', 'block');
        });

      });
    } else {
      resultDropdown.empty();

    }
  });

  // Set search input value on click of result item
  $(document).on("click", ".result", function() {
    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
    $(this).parent(".result").empty();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- header.php -->

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

推荐答案

代码中的主要问题是有一个focusout事件处理程序,该处理程序在每次搜索输入松散时都会触发.当点击结果时,这一事件也会发生.

不幸的是,这样的事件会在结果上的Click事件发生之前发生,因此一旦您将它们隐藏在第一个处理程序中,Click处理程序就不会再触发.

实现相同行为的一种快捷方法是只将一个Click事件处理程序附加到整个文档,并每次判断所单击的元素是否有#searchboxy个父元素,以便更好地基于条件执行逻辑.在第一种情况下,它将隐藏结果,而在第二种情况下,它不会.

出于演示的目的,我发明了一个来自您的API的定制结果,它不清楚将返回什么类型的数据.奇怪的是,您只是将其输出附加到结果html.我没碰它.

我还更改了您在结果项上捕获Click事件的方式.将事件处理程序仅附加到父结果一次.

//makeSearch is replacing your fetch to an unreachable url
//but you didn't explain what's supposed to return.. so I'm inventing a raw html
const makeSearch = (term) => {
  return new Promise((resolve, reject) => {
    resolve(`
      <ul>
        <li>Result1</li>
        <li>Result2</li>
        <li>Result3</li>
      </ul>`
    );    
  });
}

//on click on the whole document
$(document).on('click', function(event){  
  //if the clicked element doesn't belong to the group #searchboxy
  if(!event.target.closest('#searchboxy')){
    //hides the .result
    $('.result').css('display', 'none');
  }
});

//on focusin on the input text, shows the .result
$("#searchboxy").on('focusin', function() {      
  $('.result').css('display', 'block');
});

//on click on the .result box...
$(document).on("click", ".result", function(event) {  
  const textOfClickedResultElement = event.target.innerText;  
  $(this).parents(".search-box").find('input[type="text"]').val( textOfClickedResultElement);
  $(this).parent(".result").empty();
});

$(document).ready(function() {

  $('.search-box input[type="text"]').on("keyup input", function() {
    /* Get input value on change */
    var inputVal = $(this).val();
    var resultDropdown = $(this).siblings(".result");
    if (inputVal.length) {
      
      //$.get("includes/searchbar.inc.php", {
      //  term: inputVal
      //})
      
      //I replaced your search request with a bogus promise for the sake of the demo
      makeSearch(inputVal)
        .then(function(data) {          
          // Display the returned data in browser
          //!this is weird.. you are outputting the fetched data as is in the html! (I left it untouched)
          resultDropdown.html(data);
          $('.result').css('display', 'block');
        });
    } else {
      resultDropdown.empty();
    }
  });
  
});
.info{
  margin-bottom: 10px;
}

#searchboxy{
  border: dashed 3px lightgray;
  padding: 10px 10px;
}

#searchboxy input{
  width: 15rem;
}

#resultsearch{
  border: solid 1px gray;
  display: none;
  margin-top: 1rem;
}

#resultsearch li{
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- header.php -->

<div class="info">
  Start typing inside the textbox to show the search results.<br>
  Clicking anywhere outside the dashed borders, will hide the results.<br>
  Giving focus to the textbox, will show the results.<br>
  If you click any single result item, its value will be pushed in the search box.
</div>

<div class="search-box" id="searchboxy">
  <input type="text" autocomplete="off" placeholder="Search for a game or genre..." />
  <div class="result" id="resultsearch"></div>
</div>

Html相关问答推荐

如何防止SVG图标出现断行?

D3.js—分组条形图—更新输入数据时出错

容器内的SVG图像没有响应

为什么在添加文本时网格区域会调整大小?

创建带有弯曲边框的水平时间线

摆动的html标签

SVG动画只有在打开S开发工具的浏览器时才开始播放

在R中从网页上的特定iframe中提取图形数据

`table>;的消失;tbody:nth子级(1)`HTML

页面文件夹内的 HTML 页面未加载主目录的 style.css

在 HTML 视频上环绕文本叠加

为什么我的图像在悬停时与固定顶部栏重叠?

当我们在vue中使用截断大文本时如何显示标题属性?

将组件移动到页面底部 Angular

我正在使用 NVDA 并多次读取关闭按钮,但它的读取非常完美

如何将背景与之前的内容正确对齐

pandas `to_html()` - 如何只使特定的行有边框

右对齐 bootstrap 导航项而不是下拉菜单

项目的水平列表:倒数第二个项目居中,而最后一个项目占据所有剩余空间

如何使用 :hover zoom 重叠图像?