반응형
jQuery에서 키 누르기 사이의 작업 지연
jQuery에서 키 누르기 사이의 작업을 지연하려면 어떻게 해야 합니까?예를 들어,
이런 게 있어요.
if($(this).val().length > 1){
$.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
사용자가 계속 타이핑을 할 경우 데이터 게시를 방지하고 싶습니다.그럼 어떻게 하면 0.5초의 지연을 줄 수 있을까요?
jQuery의 데이터 기능을 사용하여 다음과 같은 작업을 수행할 수 있습니다.
$('#mySearch').keyup(function() {
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(search, 500);
$(this).data('timer', wait);
});
function search() {
$.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
여기서 가장 큰 장점은 글로벌 변수가 곳곳에 없다는 것입니다.필요에 따라 setTimeout의 익명 함수로 이 기능을 정리할 수 있습니다.그냥 예를 최대한 깔끔하게 하려고 하면 됩니다.
사용자가 키를 누르면 리셋되는 타임아웃으로 기능을 랩하기만 하면 됩니다.
var ref;
var myfunc = function(){
ref = null;
//your code goes here
};
var wrapper = function(){
window.clearTimeout(ref);
ref = window.setTimeout(myfunc, 500);
}
그런 다음 주요 이벤트에서 "wrapper"를 호출하기만 하면 됩니다.
이 문제를 해결할 수 있는 좋은 플러그인이 있습니다.j쿼리 스로틀/데바운스
Nick의 답변은 완벽하지만 첫 번째 이벤트를 즉시 처리하는 것이 중요할 경우 다음을 수행할 수 있습니다.
$(selector).keyup(function(e){ //or another event
if($(this).val().length > 1){
if !($.data(this, 'bouncing-locked')) {
$.data(this, 'bouncing-locked', true)
$.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
self = this
setTimeout(function() {
$.data(self, 'bouncing-locked', false);
//in case the last event matters, be sure not to miss it
$(this).trigger("keyup"); // call again the source event
}, 500)
}
}
});
다음과 같은 기능으로 포장할 수 있습니다.
var needsDelay = false;
function getSuggestions(var search)
{
if(!needsDelay)
{
needsDelay = true;
setTimeout("needsDelay = false", 500);
if($(this).val().length > 1){
$.post("stuff.php", {nStr: "" + search + ""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}else{
$('#suggestions').hide();
}
});
}
}
}
이렇게 하면 ping을 몇 번 해도 500밀리초마다 검색하지 않습니다.
언급URL : https://stackoverflow.com/questions/2410937/delaying-actions-between-keypress-in-jquery
반응형
'programing' 카테고리의 다른 글
대응: 기존 컴포넌트에 소품 추가 (0) | 2023.03.08 |
---|---|
반응 제어 구성 요소와 제어되지 않는 구성 요소란 무엇입니까? (0) | 2023.03.08 |
타이프스크립트:리액트에 이력 오브젝트의 타입 체크를 추가하는 방법 (0) | 2023.02.26 |
Angularjs 중첩 상태: 3 수준 (0) | 2023.02.26 |
리액트 프로젝트에 SCSS 스타일을 추가하는 방법 (0) | 2023.02.26 |