88

入力テキストボックスへの文字の入力を(入力中ではなく)停止した直後にイベントをトリガーしたい。

私は試しました:

$('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の代わりに単純なアラートを使用して同じ問題を示します。

これに対する解決策はありますか、それとも私はこれに悪いアプローチを使用していますか?

4

13 に答える 13

174

(あなたがそうであるように)を使用する必要が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>

次の場合に実行されます。

  1. タイムアウトが経過した、または
  2. ユーザーがフィールドを切り替えた(blurイベント)

(いずれか早い方)

于 2012-12-26T14:52:31.497 に答える
78

解決:

これが解決策です。ユーザーが指定された時間入力を停止した後に関数を実行する:

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 );
});
于 2013-08-28T10:00:24.337 に答える
17

underscore.jsの「debounce」を使用できます

$('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) );

これは、キーを500ミリ秒押した後に関数呼び出しが実行されることを意味します。ただし、500ミリ秒前に別のキーを押すと(別のキー押下イベントが発生)、前の関数の実行は無視(デバウンス)され、新しい500ミリ秒のタイマーの後に新しい関数が実行されます。

追加情報として、_。debounce(func、timer、true)を使用すると、最初の関数が実行され、後続の500msタイマーを伴う他のすべてのキー押下イベントが無視されます。

于 2014-06-11T17:06:18.690 に答える
10

デバウンスが必要です!

これがjQueryプラグインで、デバウンスについて知っておく必要があるのはこれだけです。Googleからここに来て、UnderscoreがアプリのJSoupに組み込まれている場合は、すぐにデバウンスされます。

于 2013-11-06T09:47:25.840 に答える
9

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
});

フィドル

お役に立てれば。

于 2019-02-11T11:17:05.580 に答える
7

洗浄液:

$.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;
};
于 2015-02-24T11:48:04.797 に答える
3

正確にそれを行う私が作ったいくつかの簡単なプラグインがあります。提案されたソリューションよりもはるかに少ないコードで済み、非常に軽量です(〜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
});

ここで何が起こるかです:

ユーザーがキーを押すたびに、入札は次の200ミリ秒間「遅延」(バンプ)されます。再び「ぶつかる」ことなく200msが経過すると、コールバックが発生します。

また、入札を停止する(たとえば、ユーザーがescを押すか、外部入力をクリックした場合)と、コールバックをすぐに終了して起動する(たとえば、ユーザーがEnterキーを押した場合)ための2つの追加機能があります。

searchBid.stop();
searchBid.finish(valueToPass);
于 2015-04-23T11:39:07.173 に答える
1

単純な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>
于 2015-02-22T01:25:27.503 に答える
0

時計をリセットしたいだけなのに、なぜそんなに多くのことをするのですか?

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);
});

WordPressで作業している場合は、このすべてのコードを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);
        });
});
于 2018-08-28T15:51:04.217 に答える
0

HTMLの属性onkeyup="myFunction()"を使用し<input>ます。

于 2020-05-05T11:05:45.377 に答える
0

useDebouncedCallbackを使用して、reactでこのタスクを実行できます。

import {useDebouncedCallback} from'use-debounce'; -インストールされていない場合は、同じようにnpmpackgeをインストールします

const [searchText, setSearchText] = useState('');

const onSearchTextChange = value => {
    setSearchText(value);
  };

//call search api
  const [debouncedOnSearch] = useDebouncedCallback(searchIssues, 500);
  useEffect(() => {
    debouncedOnSearch(searchText);
  }, [searchText, debouncedOnSearch]);
于 2021-02-04T10:23:18.710 に答える
0

これは私がformControlで使用しているものです。わたしにはできる。

this.form.controls[`text`].valueChanges
  .pipe(debounceTime(500), distinctUntilChanged())
  .subscribe((finalText) => {
    yourMethod(finalText);
});
于 2021-08-04T09:50:43.520 に答える
-1

私の考えでは、ユーザーはその入力に集中し続けないと書き込みを停止します。このためにあなたは「blur」と呼ばれる関数を持っています

于 2012-12-26T16:49:26.093 に答える