为什么第一次点击网格视图中的单选按钮毫无作用

Why does the first click on a radio button in a gridview do nothing?

本文关键字:单选按钮 作用 视图 第一次 网格 为什么      更新时间:2024-04-17

我有一个网格视图,它有一列单选按钮。我有一个javascript函数,它只允许用户单击一个单选按钮。当你第一次点击网格视图时,什么也没发生。之后的每一次点击都很好。

更新:如果我直接点击单选按钮,第一次确实有效,但如果我点击行,我必须点击两次。

<script type="text/javascript">
    function SelectSingleRadiobutton(rdbtnid) {
        var rdBtn = document.getElementById(rdbtnid);
        var rdBtnList = document.getElementsByTagName("rbTypeGroup");
        for (i = 0; i < rdBtnList.length; i++) {
            if (rdBtnList[i].type == "radio" && rdBtnList[i].id != rdBtn.id) {
                rdBtnList[i].checked = false;
            }
        }
    }
</script>

<asp:GridView ShowHeader="false" SkinID="noborder" runat="server" ID="gvType" AutoGenerateColumns="false"
                        OnRowDataBound="gvType_RowDataBound" ClientIdMode="Predictable">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButton ID="optValue" runat="server" Name="options" Style="cursor: default;" Tag="rbTypeGroup" OnClick="SelectSingleRadiobutton(this.id)"/>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" />
        <asp:BoundField DataField="Description" />
    </Columns>
</asp:GridView>
protected void gvType_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        HibConfig.IncidentType type = (HibConfig.IncidentType)e.Row.DataItem;
        RadioButton rdo = ((RadioButton)e.Row.FindControl("optValue"));
        rdo.Checked = incident.Type.Id == type.Id ? true : false;
        e.Row.Attributes.Add("onclick", string.Format("document.getElementById('{0}').click();", rdo.ClientID));
        e.Row.Attributes.Add("dataId", type.Id.ToString());
    }
}

在初始化JS之后,可能会加载网格视图。我想你看到的是,在最初的页面加载中,你的js没有gridview的上下文。您最初单击网格行会导致回发,然后会加载JS文件。如果您使用Jquery,您可能希望将JS封装在document.ready()$function() call中。另一种选择是尝试在文档底部加载JS,以确保DOM已经呈现。我已经有一些JS文件"破坏"或松散的网页上下文与asp元素。Postbacks可能会导致JS 出现许多问题