【问题标题】:How do I call a JavaScript function from my code behind, the function being on a separate .js file? [duplicate]如何从后面的代码中调用 JavaScript 函数,该函数位于单独的 .js 文件中? [复制]
【发布时间】:2013-07-31 20:09:29
【问题描述】:

后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
      Page.ClientScript.RegisterClientScriptBlock(GetType(), "MyKey", "CreateNotificationTree(" + UserId + ")", true);
}

.js 文件:

function CreateNotificationTree(UserId)
{
    var data = new kendo.data.HierarchicalDataSource({
        transport: {
            read: {
                url: "../api/notifications/byuserid/" + UserId,
                contentType: "application/json"
            }
        },
        schema: {
            model: {
                children: "notifications"
            }
        }
    });

    $("#treeview").kendoTreeView({
        dataSource: data,
        loadOnDemand: true,
        checkboxes: {
            checkChildren: true
        },
        dataTextField: ["notificationType", "NotificationDesc"]
    });
}

标记(我需要这个吗?):

<script type="text/javascript">
            $(document).ready(CreateNotificationTree(UserId));
</script>

这不起作用。树视图未加载到页面上。

【问题讨论】:

标签: c# javascript


【解决方案1】:

在您的script 块中,您没有分配CreateNotificationTree 以在$(document).ready 上调用,而是在此处调用它。正确的做法是:

<script type="text/javascript">
   $(document).ready(function () {
      CreateNotificationTree(<%= this.UserId.ToString() %>);
   });
</script>

那么Page_Load 中的RegisterClientScriptBlock 就不需要了。

第二种选择是不使用$(document).ready,而是调用RegisterStartupScript(当所有DOM元素都可用时,它会在页面底部编写脚本)而不是Page_Load中的RegisterClientScriptBlock

【讨论】:

  • 谢谢!这成功了! :)
【解决方案2】:

使用

ClientScriptManager.RegisterStartupScript

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多