我编写了一个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函数Change Event?
答案 0 :(得分:17)
或者你也可以这样做:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
答案 1 :(得分: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>
答案 2 :(得分: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);
}