从代码隐藏错误调用javascript函数

时间:2012-08-10 19:10:10

标签: javascript asp.net code-behind

我试图从aspx页面调用我的母版页中加载的一个javascript函数。

以下是我目前使用的代码:

ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "showNotifier", "showNotifier(3000,'green','test');", True)

javascript代码是这样的:

function showNotifier(delayTime, color, theMsg) {
    var theDivName = '#Notifier';
    e.preventDefault();
    $(theDivName).css("background", color);
    $(theDivName).text(theMsg);
    $(theDivName).animate({ top: 0 }, 300, null);
    $(theDivName).css("position", "fixed");

    //Hide the bar
    $notifyTimer = setTimeout(function () {
        $(theDivName).animate({ top: -100 }, 1500, function () {
            $(theDivName).css("position", "absolute");
        });
    }, delayTime);
});

这就是我的代码背后调用的地方:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "showNotifier", "showNotifier(3000,'green','test');", True)
    End If
End Sub

当我运行我的页面并加载该aspx页面时,它会显示以下错误:

Microsoft JScript runtime error: 'showNotifier' is undefined.

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:2)

改为使用RegisterClientScriptBlock

并将你的电话换成$(function(){...}):

;$(function() {showNotifier(3000,'green','test');});

UPDATE :所以你的VB代码看起来像这样:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "showNotifier", ";$(function() {showNotifier(3000,'green','test');});", True)
    End If
End Sub

UPDATE 2 您的js函数有一些语法错误:

function showNotifier(delayTime, color, theMsg) {
    var theDivName = '#Notifier';
    // 'e' is not declared -- e.preventDefault();
    $(theDivName).css("background", color);
    $(theDivName).text(theMsg);
    $(theDivName).animate({ top: 0 }, 300, null);
    $(theDivName).css("position", "fixed");

    //Hide the bar
    $notifyTimer = setTimeout(function () {
        $(theDivName).animate({ top: -100 }, 1500, function () {
            $(theDivName).css("position", "absolute");
        });
    }, delayTime);
}// ); - this should not be here