Assuming that your ul
has an id
of theList
, the following would be one way of doing it.
<input type="text" onkeyup="filter(this)" />
<script language="javascript" type="text/javascript">
function filter(element) {
var value = $(element).val();
$("#theList > li").each(function() {
if ($(this).text().search(value) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
}
</script>
If you don't wish to have case-sensitive filter then add .toLowerCase()
to these lines like so:
var value = $(element).val().toLowerCase();
if ($(this).text().toLowerCase().search(value) > -1)
Alternatively for a more concise version based on what Marek Tihkan posted you could replace the each() loop with the following. Not sure whether this would perform better or worse.
$('#theList > li:not(:contains(' + value + '))').hide();
$('#theList > li:contains(' + value + ')').show();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…