2009-07-02 82 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以瞭解此處發生了什麼。