すべての行に 1 つのセルを含むテーブルがあり、その中にチェックボックスとそのチェックボックスのラベルがあります。
入力されたテキストに基づいて行を非表示にするために私がやろうとしていること。
基本的にこれは名前のリストであり、入力されたテキストを含まないものをフィルタリング/非表示にしたい。
これは私の機能です:
$(function () {
$('#user_name').keyup(function () {
if ($.trim($('input#user_name').val()) == '') {
$('table.myList >tbody >tr').each(function (index, value) {
$(this).css("display", "block");
});
} else {
$('table.myList >tbody >tr').each(function (index, value) {
if ($(this).find('td > label').length > 0) {
if ($(this).find('td > label').html().toLowerCase().indexOf($.trim($('input#user_name').val()).toLowerCase()) >= 0) {
$(this).css("display", "block");
} else {
$(this).css("display", "none");
}
}
});
}
});
});
テーブルに 40 件のレコードがある場合、このコードは機能しますが、リストを 500 に増やすと速度が低下し、時間の経過とともにブラウザがクラッシュします。
このコードを改善してより高速に動作させる方法を探しています。
モックアップ コードへのリンクは次のとおりです: http://jsfiddle.net/gGxcS/
==更新==
@scessor と @nnnnnn の回答に基づく私の最終的な解決策は次のとおりです。
$(function () {
var $tableRows = $('table.myList tr');
var lastInput = '';
$('#user_name').keyup(function () {
var sValue = $.trim($('input#user_name').val());
if(lastInput==sValue) return;
if (sValue == '') {
$tableRows.show();
} else {
$tableRows.each(function () {
var oLabel = $(this).find('label');
if (oLabel.length > 0) {
if (oLabel.text().toLowerCase().indexOf(sValue.toLowerCase()) >= 0) {
$(this).show();
} else {
$(this).hide();
}
}
});
lastInput=sValue;
}
});
$('img.removeSelections').click(function () {
$('table.myList input[type="checkbox"]').prop("checked", false);
})
});