2

約 200 項目のリストがあります (表の行):

<tr><td><h5>Title</h5></td>
    <td class="nazwa">some text</td>
    <td>Some additional stuff</td>
</tr>

検索された文字列に一致する場合に項目をフィルター処理 (表示または非表示) する jQuery 関数を作成しました

jQuery.fn.filterItems = function(str){
    var title = jQuery(this).find("h5").text().toLowerCase();
    var name = jQuery(this).find(".nazwa").text().toLowerCase();
    if( title.search( str ) < 0 && name.search( str ) < 0 ){
        jQuery(this).hide().removeClass("visible");
    }
    else{
        jQuery(this).show().addClass("visible");
    }
    return this;
}

ユーザーが検索入力に何かを入力するたびに、項目が自動的にフィルター処理され、入力に一致する項目が表示されます。

jQuery("#search_items").on("input", function(){
        var s = jQuery(this).val();
        if(s != ""){
           jQuery('.list-of-items tr').each(function(){
               jQuery(this).filterItems( s.toLowerCase() );
           });
        }
        else{
            jQuery('.list-of-items tr').show().addClass("visible");
        }
    });

これは PC では問題なく動作しますが、モバイル デバイスではパフォーマンスの問題がいくつかあります。入力とフィルターの反応の間にかなりの遅延がある場合があります。

リソースのパフォーマンス/使用に関して、このライブ検索を最適化するにはどうすればよいですか?

4

1 に答える 1

0

これは少し役立つかもしれません: https://davidwalsh.name/javascript-debounce-function .

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
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);
    };
};

イベント関数(あなたの場合input)をdebounce()上からラップする必要があります。

デバウンスとスロットルについてもっと読む

angular を使用するプロジェクトがある場合は、はるかに簡単かつ高速になります: https://docs.angularjs.org/api/ng/filter/filter

于 2016-01-22T16:44:27.720 に答える