我在ASP.Net中有一个名为timer()的javascript函数。在代码隐藏中,我有一个
if (!Page.IsPostBack)
并且在其中我有一个触发此行的函数:
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "timerscript", "timer()", true);
当我运行它时,我收到以下错误:
Microsoft JScript Runtime Error: 'timer' is undefined
当我查看代码时,看起来像site.master已加载,但我实际加载的页面上没有任何内容已加载。
我尝试将我的计时器代码放在site.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)告诉我如何编辑此脚本以便它将运行在site.master之外?
我应该补充一点,ScriptManager.RegisterClientScriptBlock行在页面加载后触发的所有其他地方都能正常工作,所以我知道它有效。唯一不起作用的地方是初始页面加载。
答案 0 :(得分:0)
您可以尝试使用客户端脚本,尝试使用Page.ClientScript
下的方法例如:
Page.ClientScript.RegisterStartupScript
答案 1 :(得分:0)
感谢epascarello的建议,我终于有了这个工作:
ScriptManager.RegisterStartupScript(UpdatePanel4, UpdatePanel4.GetType(), "timerscript", "timer();", true);
有一点需要注意(这让我疯了);当你使用它时,需要在你的脚本名称后面加一个分号,而在使用ScriptManager.RegisterClientScriptBlock时我不需要一个分号。没有那个分号,它就行不通。