【问题标题】:Call Javascript function multiple times from code behind从后面的代码中多次调用 Javascript 函数
【发布时间】:2018-03-21 09:35:30
【问题描述】:

我在 C# 中有以下按钮事件处理程序。我想用不同的参数调用相同的 javascript 函数。

protected void Button1_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < 10; i++)
                {
                    string script = String.Format("test({0},{1})", i.ToString(), i.ToString() + 1);
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
                    "testFunction", script, true);
                }
            }

【问题讨论】:

    标签: javascript c# webmethod


    【解决方案1】:

    定义你的 js 方法,如:

    <script type="text/javascript">
    function UpdateTime(time) {
        document.getElementById("<%=lblTime.ClientID %>").innerHTML = time;
    }
    

    然后在你的代码后面,使用:

    protected void UpdateTime(object sender, EventArgs e)
    {
        string time = DateTime.Now.ToString("hh:mm:ss tt");
        string script = "window.onload = function() { UpdateTime('" + time + "'); };";
        ClientScript.RegisterStartupScript(this.GetType(), "UpdateTime", script, true);
    }
    

    源码和演示here

    【讨论】:

    • 我想在for循环中调用一个javascript函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多