I have a search bar on a website project I'm working on. The search runs an AJAX call which displays a list of users who goes by the searched name, or a name containing the searched phrase. When the user focuses out of the search bar, the result list gets hidden. Problem is, when the user wants to click on one of the people in the results, the list still gets hidden and the link in the results list is not clicked. Here is the code:
$('#searchBar').on('input', function() {
$.ajax({ url: "personsearch.php?name=" + $('#searchBar').val(), success: function(result) {
$('#searchResultList').html(result);
$('#searchResultList').css('display', 'block');
}});
});
$('#searchBar').focusout(function(event) {
$('#searchResultList').css('display', 'none');
});
Snippet of what the actual search bar and result list looks like:
<div id="search">
<input id="searchBar" type="text">
<div id="searchResultList">
<div class="result">
<a href="person.php?id=username">Example Name</a>
</div>
</div>
</div>
Is there any way to get the href to fire off before the jQuery focusout() event, or can the same result be achieved in any other way?
Thanks! I'm sorry if the question is a duplicate, I have looked for answers to my question in previous threads but I couldn't find one.
答案 0 :(得分:0)
通过在div之外寻找鼠标点击来解决问题:
$(document).click(function(event) {
if(!$(event.target).closest('#search').length) {
$('#searchResultList').css('display', 'none');
}
});