我正在尝试调用从 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/