问题
If you are trying to hide and show children based on an input's value with jQuery it will cause performance issue while typing. To avoid calling the filter function after every character, use the debounce method of lodash.
html
<input id="search" />
<div>
<div class="child">foo</div>
<div class="child">bar</div>
....
</div>
javasrcript
var filterChildren = function() {
var value = $(this).val().toLowerCase();
$(".child").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
};
$("#search").on("keyup", _.debounce(filterChildren, 300));
Do not miss to import Lodash and jQuery.
PS: this is part of the answer of the this post: How to hide the parent div if all its child div are hidden?
回答1:
I propose another solution without lodash. Just create a map on page load with your elements (assuming they do not change and are created only once on page load).
$(document).ready(function(){
var map = {};
$('.child').each(function(i,el){
map[$(el).text().toLowerCase()] = $(el);
});
$('.child').toggle(false);
$('#search').on('keyup', function(){
$('.child').toggle(false);
var el = map[$(this).val().toLowerCase()];
if (el)
$(el).toggle(true);
});
});
Live preview
回答2:
$("#search").on("keyup", _.debounce(filterChildren, 300));
function debounce( fn, threshold ) {
var timeout;
return function debounced() {
if ( timeout ) {
clearTimeout( timeout );
}
function delayed() {
fn();
timeout = null;
}
timeout = setTimeout( delayed, threshold || 100 );
};
}
来源:https://stackoverflow.com/questions/51837825/how-to-debounce-input-with-jquery-and-lodash