简体   繁体   English

从.aspx页调用ascx Javascript函数

[英]Call a ascx Javascript function from .aspx page

I have the following .ascx page(user control): 我有以下.ascx页面(用户控制):

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MultiSelectDDL.ascx.cs" Inherits="MultiSelectDDL" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
 <link href="Styles/style.css" rel="stylesheet" type="text/css" />
<script type = "text/javascript">

    function CheckItem(checkBoxList) {
        debugger;
        var options = checkBoxList.getElementsByTagName('input');
        var arrayOfCheckBoxLabels = checkBoxList.getElementsByTagName("label");
        var s = "";

        for (i = 0; i < options.length; i++) {
            var opt = options[i];
            if (opt.checked) {
                s = s + ", " + arrayOfCheckBoxLabels[i].innerHTML;
            }
        }
        if (s.length > 0) {
            s = s.substring(2, s.length);
        }
        var TxtBox = document.getElementById("<%=txtCombo.ClientID%>");
    TxtBox.value = s;
    document.getElementById('<%=hidVal.ClientID %>').value = s;
}
</script>


<asp:TextBox ID="txtCombo" runat="server" ReadOnly="true" Width="138px" Font-Size="X-Small" CssClass="txtbox"></asp:TextBox>
<cc1:PopupControlExtender ID="PopupControlExtender111" runat="server" 
    TargetControlID="txtCombo" PopupControlID="Panel111" Position="Bottom" >
</cc1:PopupControlExtender>

<input type="hidden" name="hidVal" id="hidVal" runat="server" />

<asp:Panel ID="Panel111" runat="server" ScrollBars="Vertical" Width="142px" Height="75" BackColor="White" BorderColor="Gray" BorderWidth="1">

    <asp:CheckBoxList ID="chkList" 
        runat="server" 
        Height="75" onclick="CheckItem(this)">                                                                                                                                                                        
    </asp:CheckBoxList>

</asp:Panel>

And another normal .aspx page, in which I have placed the above user control. 还有另一个普通的.aspx页面,在其中放置了上述用户控件。

What I need to do is, from a function written in .aspx.cs I want to call the Javascript written in .ascx page. 我需要做的是,从一个用.aspx.cs编写的函数中,我想调用用.ascx页编写的Javascript。

I tried: 我试过了:

 Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem('"+ MultiSelectDDL1.ClientID +"');",true);

but it does not work. 但它不起作用。 Plz help. 请帮助。

我认为问题在于您传递的是字符串而不是DOM元素,您应该使用以下内容更改启动脚本。

Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem(document.getElementById('"+ MultiSelectDDL1.ClientID +"'));",true);

您需要传递客户端ID插入的对象

 Page.ClientScript.RegisterStartupScript(this.GetType(),"MyFunction","CheckItem(this);",true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM