此解决方案基于 Ktash 的回答。我这样做是因为我想了解更多关于 javascript、DOM 导航和 RegExp 的知识。
我用“keydown”更改了“keypress”事件,因为前一个事件不会在退格/删除时触发,所以删除所有带有退格/删除的字符仍然会过滤列表。
[默认.aspx]
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RealtimeCheckBoxListFiltering.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
window.onload = function () {
var tmr = false;
var labels = document.getElementById('cblItem').getElementsByTagName('label');
var func = function () {
if (tmr)
clearTimeout(tmr);
tmr = setTimeout(function () {
var regx = new RegExp(document.getElementById('inputSearch').value);
for (var i = 0, size = labels.length; i < size; i++)
if (document.getElementById('inputSearch').value.length > 0) {
if (labels[i].textContent.match(regx)) setItemVisibility(i, true);
else setItemVisibility(i, false);
}
else
setItemVisibility(i, true);
}, 500);
function setItemVisibility(position, visible)
{
if (visible)
{
labels[position].style.display = '';
labels[position].previousSibling.style.display = '';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = '';
}
else
{
labels[position].style.display = 'none';
labels[position].previousSibling.style.display = 'none';
if (labels[position].nextSibling != null)
labels[position].nextSibling.style.display = 'none';
}
}
}
if (document.attachEvent) document.getElementById('inputSearch').attachEvent('onkeypress', func); // IE compatibility
else document.getElementById('inputSearch').addEventListener('keydown', func, false); // other browsers
};
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:TextBox runat="server" ID="inputSearch" ClientIDMode="Static" />
</td>
</tr>
<tr>
<td>
<asp:CheckBoxList runat="server" ID="cblItem" ClientIDMode="Static" RepeatLayout="Flow" />
</td>
</tr>
</table>
</form>
</body>
</html>
[默认.aspx.cs]
using System;
using System.Collections.Generic;
namespace RealtimeCheckBoxListFiltering
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
cblItem.DataSource = new List<string>() { "qwe", "asd", "zxc", "qaz", "wsx", "edc", "qsc", "esz" };
cblItem.DataBind();
}
}
}