65.9K
CodeProject 正在变化。 阅读更多。
Home

CheckBoxList 像 RadioButtonList 一样工作

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2投票s)

2013年1月3日

CPOL
viewsIcon

17973

复选框像单选按钮一样工作。

引言

本文介绍如何使用 JavaScript 使 CheckBoxList 像 RadioButtons 一样工作。

使用代码

只需将以下代码放置在您的 .ASPX 页面的 head 部分

<script type="text/javascript" language="javascript">
    function SetChkBx(event) {
        var chkBoxCount = document.getElementById('<%= chkList1.ClientID %>').getElementsByTagName("input");
        for (i = 0; i < chkBoxCount.length; i++) {
            if (chkBoxCount[i].type == 'checkbox')
                chkBoxCount[i].checked = false;
        }
        if (event.target == null) {
            event.srcElement.checked = true;
            alert("You selected " + event.srcElement.value);
        }
        else {
            event.target.checked = true;
            alert("You selected " + event.target.value);
        }
    }
</script>

兴趣点 

以下是代码,其中使用了始终为 null 的 event.target,适用于 IExplorer。 在 IExplorer 中使用 event.srcElement,它告诉浏览器有关源元素的信息,而对于其他浏览器,event.target 不为 null。 因此,对于其他浏览器,我们使用它。

将以下标签放置在您的 <Form> 标签下。

<asp:CheckBoxList ID="chkList1" runat="server" RepeatDirection="Vertical" 
    RepeatLayout="Flow" OnClick="javascript:SetChkBx(event);">
    <asp:ListItem>Apple</asp:ListItem>
    <asp:ListItem>Mango</asp:ListItem>
    <asp:ListItem>Banana</asp:ListItem>
    <asp:ListItem>Guava</asp:ListItem>
    <asp:ListItem>Grapes</asp:ListItem>
</asp:CheckBoxList>
© . All rights reserved.