2013年9月30日 星期一

[轉貼] 動態註冊JavaScript至Client端

出處:http://welkingunther.pixnet.net/blog/post/27831277

因為JavaScript是直譯語言,所以有時JavaScript的位置不同會有所不同的影響
這邊介紹三種方法
Page.ClientScript.RegisterClientScriptBlock
Page.ClientScript.RegisterStartupScript
Page.ClientScript.RegisterClientScriptInclude
以下是三種方法的差別
//Block的是將JavaScript寫到Client端HTML裡的<form>下面
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "test1", "function Hello1(){alert('這是Block');}", true);

//Startup的是將JavaScript寫到Client端HTML裡的</form>上面 
Page.ClientScript.RegisterStartupScript(this.GetType(), "test2", "function Hello2(){alert('這是Startup');}", true);

//Include的是將JavaScript寫到Client端HTML裡的<form>下面 
Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "test3", Page.ResolveUrl("~/myscript/cool.js"));
這個cool.js的內容是function Hello3() { alert('這是Include'); }

拉一個Asp.net的Button,設定onclientclick="Hello1()"就可以呼叫上面的Hello1()或Hello2()或Hello3()

最後補上產生至Client端的HTML碼

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>

</title></head>
<body>
    <form name="form1" method="post" action="Default3.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRk3NA1059Lb5lxBBIrLbEvSBZoXPM=" />
</div>

下面這行是Page.ClientScript.RegisterClientScriptBlock產生的
<script type="text/javascript">
//<![CDATA[
function Hello1(){alert('這是Block');}//]]>
</script>

下面這行是Page.ClientScript.RegisterClientScriptInclude產生的
<script src="/asptest/myscript/cool.js" type="text/javascript"></script>
<div>

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKY7vG1DwKM54rGBjWTeFqv66eWS6quxOyCE/m7DVHC" />
</div>
    <div>
   
    </div>
    <input type="submit" name="Button1" value="Button" onclick="Hello3();" id="Button1" />
   
下面這行是Page.ClientScript.RegisterStartupScript產生的
<script type="text/javascript">
//<![CDATA[
function Hello2(){alert('這是Startup');}//]]>
</script>

</form>
</body>
</html>

沒有留言:

張貼留言