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

标签 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.

什么原因会导致这种情况?

最佳答案

改用RegisterClientScriptBlock

并将您的调用包装在 $(function() { ... } ) 中:

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

更新:因此您的 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

更新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

关于javascript - 从代码隐藏错误调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907821/

相关文章:

javascript - jquery正则表达式替换2个分隔符之间

javascript - 如何实现这段php代码

c# - 如何使用 Ninject InRequestScope 处理异步调用?

asp.net - 堆栈跟踪 : how to show only my code?

c# - 在 Visual Studio 2012 中,页面控件和事件转到代码隐藏的哪个位置?

c# - c# 如何将asp.net页面移动到顶部

javascript - p5.speech.js 连续不会变成真的

javascript - 如何使用 javascript 在 CRM 2013 中设置 iframe src 属性集?

.net - System.Drawing 和垃圾收集

c# - 从代码隐藏设置 silverlight 控件的视觉元素?