我有以下jQuery和
HTML,当输入的焦点丢失时隐藏搜索结果.
当点击#searchResult上的元素时,此代码用id #searchResult隐藏我的div.我想在单击#searchResult div上的元素时禁用模糊.基本上,我想隐藏< div id =“searchResult”>当焦点丢失并显示焦点时.我怎样才能做到这一点?
$(document).on("blur","#txtSearchTerm",function () { $('#searchResult').hide(); }); $(document).on("focus",function () { $('#searchResult').show(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input id="txtSearchTerm" type="text"> <div id="searchResult"> <ul> <li> <a href="http://www.google.com"> <div class="title">Google.com</div> <div class="content">Click here</div> </a> </li> <li> <a href="http://www.google.com"> <div class="title">Google.com</div> <div class="content">Click here</div> </a> </li> </ul> </div>
< div id =“searchResult”>将在每次点击其中的元素时隐藏.
解决方法
你不需要模糊事件来实现这一目标:
$(document).click(function(e) { if ($(e.target).is("div") && $(e.target).has("ul > li")){ $('#searchResult').show() } else $('#searchResult').hide() if ($(e.target).is(':focus')){ $('#searchResult').show() } })
#searchResult{ margin-top: 50px; border: 2px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input id="txtSearchTerm" type="text"> Click out the input to hide div <div id="searchResult"> <ul> <li> <a href="http://www.google.com"> <div class="title">Google.com</div> <div class="content">click here</div> </a> </li> <li> <a href="http://www.google.com"> <div class="title">Google.com</div> <div class="content">click here</div> </a> </li> </ul> </div>