在使用字符串参数引用ClientID

时间:2015-06-12 17:54:36

标签: javascript c# jquery html

我环顾四周,而且我无法找到所需的所有部分。问题是我想从多个地方调用相同的javascript函数,所以我需要将元素的ID传递给函数,以便我可以更改它们。这个想法非常简单。我只想要四个复选框在单击时调用此函数,以防止最后一个框被取消选中。这是我到目前为止所拥有的。

HTML:

<asp:CheckBox ID="cbBlue" Text="Blue" Checked="true" runat="server" />
<asp:CheckBox ID="cbGreen" Text="Green" Checked="true" runat="server" />
<asp:CheckBox ID="cbRed" Text="Red" Checked="true" runat="server" />
<asp:CheckBox ID="cbYellow" Text="Yellow" Checked="true" runat="server" />
<asp:HiddenField ID="hdnCheckCount" runat="server" Value="4" />

C#:

protected void Page_Load(object sender, EventArgs e)
{
    cbBlue.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
    cbGreen.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
    cbRed.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
    cbYellow.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
}

使用Javascript:

function checkCheck(elementID) {
    if ($('#<%=hdnCheckCount.ClientID%>').val() == 1) {
        elementID.prop("checked", true);
        return;
    }
    else {
        if (elementID.is(":checked")) {
            elementID.prop("checked", false);
            $('#<%=hdnCheckCount.ClientID%>').val($('#<%=hdnCheckCount.ClientID%>').val() - 1);
        }
        else {
            elementID.prop("checked", true);
            $('#<%=hdnCheckCount.ClientID%>').val($('#<%=hdnCheckCount.ClientID%>').val() + 1);
        }
    }
}

这可能吗?我接近了吗?另外,我有点不确定我是否需要在javascript中实际设置框的选中状态,因为我猜这已经在其他地方处理了。但是,我不确定强制它是否真的会起作用,因为在javascript函数运行后它可能仍未被检查。

1 个答案:

答案 0 :(得分:1)

由于实际上没有数据传递给后端,我建议完全在javascript中执行此操作。因为我看到你正在使用jQuery,所以我建议这样做。

首先,在所有复选框中添加一个类

<asp:CheckBox ID="cbBlue" CssClass="keepOneChecked" Text="Blue" Checked="true" runat="server" />
<asp:CheckBox ID="cbGreen" CssClass="keepOneChecked" Text="Green" Checked="true" runat="server" />
<asp:CheckBox ID="cbRed" CssClass="keepOneChecked" Text="Red" Checked="true" runat="server" />
<asp:CheckBox ID="cbYellow" CssClass="keepOneChecked" Text="Yellow" Checked="true" runat="server" />

然后使用jQuery绑定onclick事件

$(function(){ 
    //bind event
    $('.keepOneChecked').click(function(e){
        //get all the checkboxes that ARE checked
        //.keepOneChecked is applied to a span wrapping the input and label because of ASP
        var $checked = $('.keepOneChecked input:checked');
        if( $checked.length == 1){
            //if there is only 1, disable it so you can't uncheck it
            $checked.attr('disabled',true);
        }
        else{
            //otherwise a second or more just got checked so enable all of them
            $checked.attr('disabled',false);
        }
    }); 
});

至于你特别关注的问题,我认为当你有约束力时

cbRed.Attributes.Add("onclick", "checkCheck('#<%=this.ClientID%>')");

&#34;这&#34;被引用的是页面而不是元素,加上语法错误。你可以尝试:

cbRed.Attributes.Add("onclick", "checkCheck('"+cbRed.ClientID+"')");

看看是否有效,但我首先尝试仅在jQuery中进行。