입력/쓰기를 중지한 후 입력 텍스트에서 이벤트를 트리거하는 방법은 무엇입니까?
입력 텍스트 상자에 문자 입력을 중지한 후 바로 이벤트를 트리거하려는 경우
사용해 본 적이 있습니다.
$('input#username').keypress(function() {
var _this = $(this); // copy of this object for further usage
setTimeout(function() {
$.post('/ajax/fetch', {
type: 'username',
value: _this.val()
}, function(data) {
if(!data.success) {
// continue working
} else {
// throw an error
}
}, 'json');
}, 3000);
});
그러나 이 예제에서는 입력된 모든 문자에 대해 시간 초과가 발생하며 20자를 입력하면 약 20개의 AJAX 요청이 수신됩니다.
이 바이올린에서 저는 AJAX 대신 간단한 경고로 동일한 문제를 보여줍니다.
이에 대한 해결책이 있습니까? 아니면 이에 대한 잘못된 접근법을 사용하는 것입니까?
다음을 사용해야 합니다.setTimeout
제한을 계속 재설정할 수 있도록 참조도 저장합니다.다음과 같은 것:
//
// $('#element').donetyping(callback[, timeout=1000])
// Fires callback when a user has finished typing. This is determined by the time elapsed
// since the last keystroke and timeout parameter or the blur event--whichever comes first.
// @callback: function to be called when even triggers
// @timeout: (default=1000) timeout, in ms, to to wait before triggering event if not
// caused by blur.
// Requires jQuery 1.7+
//
;(function($){
$.fn.extend({
donetyping: function(callback,timeout){
timeout = timeout || 1e3; // 1 second default timeout
var timeoutReference,
doneTyping = function(el){
if (!timeoutReference) return;
timeoutReference = null;
callback.call(el);
};
return this.each(function(i,el){
var $el = $(el);
// Chrome Fix (Use keyup over keypress to detect backspace)
// thank you @palerdot
$el.is(':input') && $el.on('keyup keypress paste',function(e){
// This catches the backspace button in chrome, but also prevents
// the event from triggering too preemptively. Without this line,
// using tab/shift+tab will make the focused element fire the callback.
if (e.type=='keyup' && e.keyCode!=8) return;
// Check if timeout has been set. If it has, "reset" the clock and
// start over again.
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
// if we made it here, our timeout has elapsed. Fire the
// callback
doneTyping(el);
}, timeout);
}).on('blur',function(){
// If we can, fire the event since we're leaving the field
doneTyping(el);
});
});
}
});
})(jQuery);
$('#example').donetyping(function(){
$('#example-output').text('Event last fired @ ' + (new Date().toUTCString()));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="example" />
<p id="example-output">Nothing yet</p>
다음과 같은 경우에 실행됩니다.
- 시간 초과가 경과되었거나
- 필드사용자 전환 필드)
blur
(둘 중 먼저 오는 것)
솔루션:
여기 해결책이 있습니다.사용자가 지정된 시간 동안 입력을 중지한 후 기능 실행:
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
사용.
$('input').keyup(function() {
delay(function(){
alert('Hi, func called');
}, 1000 );
});
언더스코어.js "데바운스"를 사용할 수 있습니다.
$('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) );
즉, 키를 누른 후 500ms 후에 함수 호출이 실행됩니다.그러나 500ms 이전에 다른 키를 누르면(다른 키 누름 이벤트가 실행됨) 이전 기능 실행은 무시(데바운스)되고 새 기능 실행은 500ms 타이머가 새로 생성된 후에 실행됩니다.
추가 정보를 위해 _.debounce(func, timer, true)를 사용하면 첫 번째 함수가 실행되고 이후 500ms 타이머가 포함된 다른 모든 키 누름 이벤트가 무시됩니다.
당신은 데바운스가 필요해요!
여기 jQuery 플러그인이 있고, 여기 당신이 디바운스에 대해 알아야 할 모든 것이 있습니다.만약 당신이 구글에서 이곳으로 오고 있고 언더스코어가 당신의 앱의 JSoup에 들어갔다면, 그것은 바로 시작되었습니다!
은 할해야합다를 해야 합니다.setTimeout
하고 를 사용합니다.clearTimeout
키 누름으로 지울 수 있습니다.
var timer = '';
$('input#username').keypress(function() {
clearTimeout(timer);
timer = setTimeout(function() {
//Your code here
}, 3000); //Waits for 3 seconds after last keypress to execute the above lines of code
});
이게 도움이 되길 바랍니다.
세척된 용액:
$.fn.donetyping = function(callback, delay){
delay || (delay = 1000);
var timeoutReference;
var doneTyping = function(elt){
if (!timeoutReference) return;
timeoutReference = null;
callback(elt);
};
this.each(function(){
var self = $(this);
self.on('keyup',function(){
if(timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function(){
doneTyping(self);
}, delay);
}).on('blur',function(){
doneTyping(self);
});
});
return this;
};
제가 만든 몇 가지 간단한 플러그인이 있습니다.제안된 솔루션보다 훨씬 적은 코드를 필요로 하며 매우 가볍습니다(~0,6kb).
처에생성항목을 만듭니다.Bid
수 보다 더 많은 객체bumped
언제라도요.모든 범프는 다음에 주어진 시간 동안 비드 콜백을 실행하는 것을 지연시킵니다.
var searchBid = new Bid(function(inputValue){
//your action when user will stop writing for 200ms.
yourSpecialAction(inputValue);
}, 200); //we set delay time of every bump to 200ms
때Bid
물체가 준비되었습니다, 우리는 해야 합니다.bump
어떻게든.에 범핑을 부착합니다.keyup
event
.
$("input").keyup(function(){
searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});
여기서 일어나는 일은 다음과 같습니다.
사용자가 키를 누를 때마다 다음 200ms 동안 입찰이 '지연'(범핑)됩니다.200ms가 다시 '범핑'되지 않고 통과되면 콜백이 실행됩니다.
또한 입찰을 중지하고(예: 사용자가 esc 또는 외부 입력을 클릭한 경우) 콜백을 즉시 완료하고(예: 사용자가 enter key를 누를 때) 실행할 수 있는 두 가지 추가 기능이 있습니다.
searchBid.stop();
searchBid.finish(valueToPass);
간단한 HTML/JS 코드를 검색해 봤는데 하나도 없었습니다.그런 다음 아래 코드를 사용하여 작성했습니다.onkeyup="DelayedSubmission()"
.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
var date = new Date();
initial_time = date.getTime();
if (typeof setInverval_Variable == 'undefined') {
setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
}
}
function DelayedSubmission_Check() {
var date = new Date();
check_time = date.getTime();
var limit_ms=check_time-initial_time;
if (limit_ms > 800) { //Change value in milliseconds
alert("insert your function"); //Insert your function
clearInterval(setInverval_Variable);
delete setInverval_Variable;
}
}
</script>
</head>
<body>
<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />
</body>
</html>
이 작업을 대응적으로 수행하려면 Debounded Callback을 사용할 수 있습니다.
'use-debounce'에서 {useDebounceCallback} 가져오기; - 설치되지 않은 경우 동일한 npm package 설치
const [searchText, setSearchText] = useState('');
const onSearchTextChange = value => {
setSearchText(value);
};
//call search api
const [debouncedOnSearch] = useDebouncedCallback(searchIssues, 500);
useEffect(() => {
debouncedOnSearch(searchText);
}, [searchText, debouncedOnSearch]);
당신이 단지 시계를 재설정하고 싶을 때 왜 그렇게 많이 합니까?
var clockResetIndex = 0 ;
// this is the input we are tracking
var tarGetInput = $('input#username');
tarGetInput.on( 'keyup keypress paste' , ()=>{
// reset any privious clock:
if (clockResetIndex !== 0) clearTimeout(clockResetIndex);
// set a new clock ( timeout )
clockResetIndex = setTimeout(() => {
// your code goes here :
console.log( new Date() , tarGetInput.val())
}, 1000);
});
워드프레스 작업을 하고 있다면, 당신은 이 모든 코드를 jQuery 블록 안에 감아야 합니다.
jQuery(document).ready(($) => {
/**
* @name 'navSearch'
* @version 1.0
* Created on: 2018-08-28 17:59:31
* GMT+0530 (India Standard Time)
* @author : ...
* @description ....
*/
var clockResetIndex = 0 ;
// this is the input we are tracking
var tarGetInput = $('input#username');
tarGetInput.on( 'keyup keypress paste' , ()=>{
// reset any privious clock:
if (clockResetIndex !== 0) clearTimeout(clockResetIndex);
// set a new clock ( timeout )
clockResetIndex = setTimeout(() => {
// your code goes here :
console.log( new Date() , tarGetInput.val())
}, 1000);
});
});
양식 컨트롤과 함께 사용합니다.저한테는 효과가 있어요.
this.form.controls[`text`].valueChanges
.pipe(debounceTime(500), distinctUntilChanged())
.subscribe((finalText) => {
yourMethod(finalText);
});
제 생각에는 사용자가 입력에 계속 집중하지 않을 때 글을 쓰는 것을 멈춥니다.이를 위해 당신은 다음과 같은 것들을 하는 "blur"라고 불리는 기능을 가지고 있습니다.
의 keyup="myFunction()" 속성을 사용합니다.<input>
당신의 html.
언급URL : https://stackoverflow.com/questions/14042193/how-to-trigger-an-event-in-input-text-after-i-stop-typing-writing
'programing' 카테고리의 다른 글
C에서 문자열을 클립보드에 복사하는 방법은 무엇입니까? (0) | 2023.08.10 |
---|---|
php의 시간대 변환 (0) | 2023.08.10 |
최대 절전 모드, ID, 오라클, 시퀀스 (0) | 2023.08.10 |
스키마 유효성 검사로 인해 스프링 부트 프로젝트가 실행되지 못함: 시퀀스 누락 [hibernate_sequence] (0) | 2023.08.10 |
하이픈 뒤에 줄 바꿈 없음 (0) | 2023.08.10 |