在页面加载时运行javascript函数
本文关键字:运行 javascript 函数 加载 | 更新日期: 2023-09-27 18:05:45
我在ASP中有一个javascript函数。Net称为timer()。在代码后面,我有一个
if (!Page.IsPostBack)
在里面我有一个函数触发这一行:
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "timerscript", "timer()", true);
当我运行这个时,我得到以下错误:
Microsoft JScript Runtime Error: 'timer' is undefined
当我看代码时,它看起来像网站。master已经加载了,但是我正在加载的页面还没有加载。
我试着把我的定时器代码在现场。master,但是它引用了我设置了计时器的页面上的一个特定字段,它不会加载。
这是我的定时器脚本:
<script type = "text/javascript">
/* Stop, Clear and Pause the timer displayed under the pause buttons */
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
document.getElementById('<%=h1.ClientID%>').innerText = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);;
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
function stp() {
clearTimeout(t);
}
function clr() {
document.getElementById('<%=h1.ClientID%>').innerText = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>
所以,任何人都可以a)告诉我如何得到这个脚本运行时,我加载我的页面,或b)告诉我如何编辑这个脚本,使其运行off site.master?
我应该添加ScriptManager。RegisterClientScriptBlock行在页面加载后触发的所有其他地方都可以正常工作,所以我知道它可以工作。唯一不工作的地方是在初始页面加载
您可以尝试使用客户端脚本,尝试Page下的方法。ClientScript
例如:Page.ClientScript.RegisterStartupScript
多亏了epascarello的建议,我终于让这个工作了:
ScriptManager.RegisterStartupScript(UpdatePanel4, UpdatePanel4.GetType(), "timerscript", "timer();", true);
有一件事要注意(这让我发疯了);当你使用这个时,你需要在你的脚本名称后面有一个分号,而我在使用ScriptManager.RegisterClientScriptBlock时不需要一个分号。如果没有分号,它将无法工作。