ASP.NET調用javascript指令碼的方法總結

來源:互聯網
上載者:User

  ASP.NET本身就提供了多種調用javascript指令碼的方法,本文總結了六種調用方法,大家根據自己的使用習慣可以選擇相應的調用方式了!

 

1、直接在前台調用 javascript 函數

 

很簡單,在 head 元素之間加入 script 元素,將 type 元素設定為 " text/javascript "

如:

<head runat="server">
<script type="text/javascript" >
function ShowName(str)
{
alert("您的名字為:("+str+")");
}
</script>
    <title>using javascript</title>
</head>

之後在body 元素間,通過事件來訪問 如 要通過button1 的單擊事件(onclientclick)來訪問 javascript 函數

樣本如下:

<asp:Button ID="Button1" runat="server" Text="Button"  onclientclick="ShowName('XXX')"  />

這時運行項目,單擊 button時,會顯示"您的名稱為XXX"

這就是一個簡單的javascript 函數.

 

2、在前台通過 js檔案 調用

 

方法與 (1)一樣 只不過需要指定 .js 檔案

樣本如下:

<head runat="server">
<script type="text/javascript" src="JScript.js">
</script>
    <title>using javascript</title>
</head>

之後在body 元素間,通過事件來訪問 如 要通過button1 的單擊事件(onclientclick)來訪問 javascript 函數

樣本如下:

//此時 .js檔案中必須有 ShowName 方法

<asp:Button ID="Button1" runat="server" Text="Button"  onclientclick="ShowName('XXX')"  />

 

3、在後台調用 javascript 函數,函數在.js檔案中

 

前台的head 元素

<head runat="server">
<script type="text/javascript" src="JScript.js">
</script>
    <title>using javascript</title>
</head>

背景需要添加如下代碼

Button1.Attributes.Add("onclick", "showname1(XXX)");

 

4、在後台調用 javascript 函數,函數寫在 .js檔案中,但並沒有在前台定義

 

//獲得.js檔案

string myscript = "JScript.js";

//註冊.js檔案, 如果此時查看源碼,會得到如下代碼

//<script> src ="JScript.js" type="text/javascript"><script>

Page.ClientScript.RegisterClientScriptInclude("myKey", myscript);

//同上
Button1.Attributes.Add("onclick", "showname1(123)");

 

5. 用Response.Write方法寫入指令碼

 

比如在你單擊按鈕後,先操作資料庫,完了後顯示已經完成,可以在最後想調用的地方寫上
Response.Write("<script type='text/javascript'>alert();</script>");

這個方法有個缺陷就是不能呼叫指令碼檔案中的自訂的函數,只能調用內建函式,具體調用自訂的函數只能在Response.Write寫上函數定 義,比如Response.Write("<script type='text/javascript'>function myfun(){...}</script>");

 

6.用ClientScript類動態添加指令碼

 

    用法如下:在想調用某個javascript指令碼函數的地方添加代碼,注意要保證MyFun已經在指令檔中定義過了。

    ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>MyFun();</script>");

這個方法比Response.Write更方便一些,可以直接呼叫指令碼檔案中的自訂函數。

注意,以上所有方法中,後台代碼都不能有轉化當前頁的代碼,比如Redirect等,要把轉頁代碼放在指令碼裡面

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.