[英]Refreshing the absolutely positioned div element
I want to create my own auto-complete component. 我想创建自己的自动完成组件。
Each time I make a change to the input, the suggested results don't appear unless I click somewhere else on the page. 每次更改输入内容时,除非单击页面上的其他位置,否则不会出现建议的结果。
How can I make it so that I see the suggested result while I make changes in the input? 如何进行更改,以便在更改输入时看到建议的结果?
$(document).ready(function() { element = document.getElementById('autocomplete-position'); var top = $('#autocomplete-position').offset().top - $('#position-relative').offset().top; var rect = element.getBoundingClientRect(); var width = element.offsetWidth; $('.autocomplete-suggestions').css('top', top).css('left', rect.left).css('width', width); $('#q').change(function() { $.ajax({ url: 'http://localhost:3000/search', data: { term: $('#q').val() }, success: function(data) { $('.autocomplete-suggestions').children().remove(); data.forEach(function(element) { $('.autocomplete-suggestions').append(' <div class="autocomplete-suggestion"><p>' + element.name + '</p></div>'); }); } }); }); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="position-relative"></div> <input type="text" name="q" id="q" autocomplete="off" /> <div id="autocomplete-position"></div> <div class="autocomplete-suggestions" style="position: absolute; z-index: 999"> </div>
If you want to search as you type, I suggest using an event other than change
. 如果您想在键入时进行搜索,建议您使用
change
以外的事件。
When change
is bound to an <input>
, "the event is deferred until the element loses focus". 当
change
绑定到<input>
,“该事件将推迟到元素失去焦点为止”。
Consider the keyup
event, which fires "when the user releases a key on the keyboard". 考虑
keyup
事件,该事件在“用户释放键盘上的键时”触发。
$('#searchInput').on('keyup',function(){ ... });
Further Recommendations: 进一步建议:
I also recommend "debouncing" the handler, which "limits the rate at which a function can fire". 我还建议“取消抖动”处理程序,这“限制了函数可以触发的速率”。
That way the AJAX won't unnecessarily fire a bunch of times in a row if someone is typing fast. 这样,如果有人快速输入,AJAX不会连续不必要地触发很多次。
So something like this: 所以像这样:
function handleError(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function searchRequest(term) {
return $.ajax({
url: 'http://localhost:3000/search',
method: 'POST',
data: {
term: term
}
});
}
function updateSuggestions(data) {
$suggestions.empty();
data.forEach(function(element) {
$('<div>', {
'class': 'autocomplete-suggestion'
}).append(
$('<p>', {
'text': element.name
})
).appendTo($suggestions);
});
}
var handleKeyUp = debounce(function() {
var term = $(this).val();
searchRequest(term)
.done(updateSuggestions)
.fail(handleError);
}, 250);
var $suggestions = $('.autocomplete-suggestions');
$('#searchInput').on('keyup', handleKeyUp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="searchInput">
<div class="autocomplete-suggestions"></div>
In this demonstration, I'm using the debounce function from David Walsh 在此演示中,我使用了David Walsh的去抖动功能
(as taken from Underscore.js). (摘自Underscore.js)。
For reference, see: 供参考,请参阅:
David Walsh - JavaScript Debounce Function David Walsh-JavaScript反跳功能
John Dugan - Demystifying Debounce in JavaScript John Dugan-用JavaScript消除反跳
StackOverflow - Can someone explain the “debounce” function in Javascript StackOverflow-有人可以解释Java语言中的“反跳”功能吗
Try keydown event: 尝试按键事件:
$('#q').on('keydown',function() {
$.ajax({
url: 'http://localhost:3000/search',
data: {
term: $('#q').val()
},
success: function(data) {
$('.autocomplete-suggestions').children().remove();
data.forEach(function(element) {
$('.autocomplete-suggestions').append(' <div class="autocomplete-suggestion"><p>' + element.name + '</p></div>');
});
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.