16

我编写了一个 JavaScript 函数,如下所示:

 function CalcTotalAmt() 
 {
    ----------
    -----------
 }

我有一个 DropDownList,

  <asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

我需要在 DropDownList 的 SelectedIndexChanged 事件中调用上述 JavaScript 函数。我尝试如下;

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
    ddl.Attributes.Add("onchange", "return CalcTotalAmt();");
}

但是 JavaScript 函数没有执行。如何在 DropDownList 更改事件中调用 JavaScript 函数?

4

3 回答 3

17

或者你也可以这样做:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
于 2012-06-02T11:39:22.237 回答
13

第一种方法:(已测试)

.aspx.cs 中的代码:

 protected void Page_Load(object sender, EventArgs e)
    {
        ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
        if (!Page.IsPostBack)
        {
            ddl.Attributes.Add("onchange", "CalcTotalAmt();");
        }
    }

    protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       //Your Code
    }

JavaScript 函数:从你的 JS 函数返回 true

   function CalcTotalAmt() 
 {
//Your Code
 }

.aspx 代码:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>

第二种方法:(已测试)

.aspx.cs 中的代码:

protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
                ddl_SelectedIndexChanged(sender, e);
            if (!Page.IsPostBack)
            {
                ddl.Attributes.Add("onchange", "CalcTotalAmt();");
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Your Code
        }

JavaScript 函数:从你的 JS 函数返回 true

function CalcTotalAmt() {
         //Your Code
     __doPostBack("ctl00$MainContent$ddl","ddlchange");
 }

.aspx 代码:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true">
        <asp:ListItem Text="a" Value="a"></asp:ListItem>
         <asp:ListItem Text="b" Value="b"></asp:ListItem>
        </asp:DropDownList>
于 2012-06-02T11:24:31.977 回答
1

您可以使用ScriptManager.RegisterStartupScript();从服务器调用任何 javascript 事件/客户端事件。例如,要使用 javascript 显示消息alert();,您可以这样做:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

准确地说,请执行此操作...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
于 2012-09-11T05:13:00.823 回答