2009-07-02 31 views
1

我可能错过了一些东西在这里根本,但它似乎相当棘手和困惑,我所以这里去...范围的Javascript与asp.net

证明我有下面的例子.aspx页面中的问题

<%@ Page Language="VB" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<script runat="server"> 
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    Response.Write("<script type=text/javascript>alert('Alert from response.write')" & ";</sc" & "ript>") 
End Sub 

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>") 
End Sub 

Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    Response.Write("<script type=text/javascript> helloWorld(); </sc" & "ript>") 
End Sub 
</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title>Untitled Page</title> 
<script type="text/javascript"> 
    function helloWorld() 
    { 
     alert('hello!'); 
    } 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
    <asp:Button runat=server ID="Button1" text=1 OnClick="Button1_Click" /> 
    <asp:Button runat=server ID="Button2" text=2 OnClick="Button2_Click" /> 
    <asp:Button runat=server ID="Button3" text=3 OnClick="Button3_Click" OnClientClick="helloWorld();" /> 
    <asp:Button runat=server ID="Button4" text=4/> 
</div> 
</form> 
</body> 
</html> 

所以,我有3个按钮,第一个调用response.write来执行JS警报..这个工程。 第二次尝试调用头标记中定义的helloWorld()。这不起作用。 第三个在response.write和onClientClick()中都调用了helloWorld() - 只有onClientClick才起作用。

有人可以解释为什么我不能使用response.write方法调用helloWorld()吗?

干杯:d

+0

做一个查看源,你会看到。 – 2009-07-02 09:25:59

+0

正如大家所说,这只是执行的顺序,但退后一步,我想不出有什么正当的理由去做你想用Repsonse做的事情。写作 – annakata 2009-07-02 09:28:03

回答

0

我认为是回复于擦拭probally在回发的将HelloWorld()的定义。尝试使用PlaceHolder将脚本标记插入到HTML中。 Rich

1

在包含该功能的HTML甚至已被下载之前,您正在调用helloWorld。

在调用它们之前定义你的函数。

(和使用验证 - 你不能有头部或身体外<script>标签。)

0

服务器端单击事件呈现任何内容之前运行。因此,即使将html元素写入响应,Response.Write也会生成脚本元素。在浏览器中使用查看源查看已写入的内容。

尝试搜索“ASP.NET页面生命周期”的帮助文档或MSDN以了解此处发生了什么。