You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在asp:BulletedList中实现点击ListItem时改变颜色

解决asp:BulletedList点击ListItem改变颜色的问题

问题根源

你之前的方案无效,核心原因是asp:BulletedList默认的DisplayMode为Text,此时<asp:ListItem>会被渲染为<li>标签内的纯文本,而非<a>标签,导致你写的a.selected选择器无法匹配到目标元素。

实现步骤

1. 调整前端控件与样式

首先修改asp:BulletedList的DisplayMode为LinkButton,让每个列表项渲染为可点击的链接元素;同时修正CSS选择器,确保能正确选中带selected类的列表项:

<style>
    #filterList ul li a {
        color: black;
        text-decoration: none; /* 可选,去掉链接下划线 */
        cursor: pointer;
    }

    #filterList ul li a.selected {
        color: red;
    }
</style>

<div id="filterList">
    <asp:BulletedList id="bl" runat="server" 
                      style="list-style-type: none;"
                      DisplayMode="LinkButton"
                      OnClick="bl_Click">
        <asp:ListItem>Option 1</asp:ListItem>
        <asp:ListItem>Option 2</asp:ListItem>
        <asp:ListItem CssClass="selected">Option 3</asp:ListItem>
        <asp:ListItem>Option 4</asp:ListItem>
        <asp:ListItem>Option 5</asp:ListItem>
    </asp:BulletedList>
</div>

2. 后台点击事件处理

在后台代码(如.aspx.cs文件)中实现BulletedList的点击事件,移除所有列表项的选中样式,再给当前点击的项添加selected类:

protected void bl_Click(object sender, BulletedListEventArgs e)
{
    // 移除所有ListItem的selected类
    foreach (ListItem item in bl.Items)
    {
        item.CssClass = "";
    }
    // 给当前点击的ListItem添加selected类
    bl.Items[e.Index].CssClass = "selected";
}

补充说明

如果你的场景不需要回发,也可以用纯JavaScript实现前端切换,避免服务器交互:

<script>
    document.querySelectorAll('#filterList ul li a').forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault(); // 阻止默认跳转(如果不需要回发)
            // 移除所有选中类
            document.querySelectorAll('#filterList ul li a.selected').forEach(el => {
                el.classList.remove('selected');
            });
            // 给当前点击的元素添加选中类
            this.classList.add('selected');
        });
    });
</script>

这种方式无需修改DisplayMode,也不需要后台事件,适合纯前端交互的场景。

内容的提问来源于stack exchange,提问作者pjakesson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 17:06:11