JS常用

100784 ワード

[一籠飯特稀オリジナル、転載は出典http://www.cnblogs.com/wanghafan/archive/2012/02/15/2352126.htmlを明記してください]
--Jquery Ajax特殊文字の転送


View Code
 1 Jquery $.Ajax     <>   html               ,      :tempStr   "<table>...</table>"  。
2
3 $.ajax({
4 type: "POST",
5 url: "../Control/Ajax_Excel.aspx",
6 data: {htmlStr:escape(tempStr)},
7 success: function(data)
8 {
9 }
10 });
11 public partial class Control_Ajax_Excel : System.Web.UI.Page
12 {
13 protected void Page_Load(object sender, EventArgs e)
14 {
15 string HtmlStr = Request.Params["htmlStr"] == null ? string.Empty : Server.UrlDecode(Request.Params["htmlStr"].ToString());
16 ...
17 }
18
19 }

--Jquery Ajaxがキャッシュされて$に入れない.ajaxのurlページのブレークポイント問題の研究と解決方法


View Code
 1     ,     $.ajax type="Post",   ajax type="Get"            ,      IE    ajax             !  ,   $.ajax     type="POST"
2 <Jquery AJAX POST GET >http://fengyan0124.blog.163.com/blog/static/11733439120104151238789/
3
4 1:GET
5 URL [ URL ]
6 URL
7 POST ( POST )
8 GET URL ?+new Date();,[ URL ]
9 WEB
10 2: . Ajax Get Post
11 Get :
12 get , 1KB , url (http header ), , URL 。 , , , , , 。 , ,get 。
13 Post :
14 POST , HTTP Web , URL , POST GET 。
15 ,GET , , , , POST 。
16 get :
17 1 get ( url ), encodeURIComponent . :var url = "update.php?username=" +encodeURIComponent(username) + "&content=" +encodeURIComponent
18 (content)+"&id=1" ;
19 Post :
20 1. header Context-Type application/x-www-form-urlencode . XmlHttpRequest SetRequestHeader("Context-Type","application/x-www- form-urlencoded;")。 :
21 xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
22 2. / , & . var name=abc&sex=man&age=18, var name=update.php?
23 abc&sex=man&age=18 var name=?abc&sex=man&age=18 ;
24 3. Send( ) , : xmlHttp.send(name); get , xmlHttp.send(null);
25 4. Get Post。 get $username = $_GET["username"]; post , $username = $_POST["username"];

--Table 2 JsonとDataTable 2 Json


View Code
 1 function Table2Json(tableid) {
2
3 var txt = "[";
4 var table = document.getElementById(tableid);
5 var row = table.getElementsByTagName("tr");
6 var col = row[0].getElementsByTagName("td");
7 for(var j = 1; j < row.length; j++) {
8 var r = "{";
9 for(var i = 0; i < col.length; i++) {
10 var tds = row[j].getElementsByTagName("td");
11 r += "\""+ col[i].innerHTML + "\"\:\""+ tds[i].innerHTML + "\",";
12 }
13 r = r.substring(0, r.length - 1)
14 r += "},";
15 txt += r;
16 }
17 txt = txt.substring(0, txt.length - 1);
18 txt += "]";
19 returntxt;
20 }
21
22 public static string DataTable2Json(DataTable dt)
23 {
24 StringBuilder JsonString = new StringBuilder();
25 if (dt != null && dt.Rows.Count > 0)
26 {
27 JsonString.Append("[ ");
28 for (int i = 0; i < dt.Rows.Count; i++)
29 {
30 JsonString.Append("{ ");
31 for (int j = 0; j < dt.Columns.Count; j++)
32 {
33 if (j < dt.Columns.Count - 1)
34 {
35 JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\",");
36 }
37 else if (j == dt.Columns.Count - 1)
38 {
39 JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"");
40 }
41 }
42 if (i == dt.Rows.Count - 1)
43 {
44 JsonString.Append("} ");
45 }
46 else
47 {
48 JsonString.Append("}, ");
49 }
50 }
51 JsonString.Append("]");
52 return JsonString.ToString();
53 }
54 else
55 {
56 return null;
57 }
58 }

--JSセル変更コントロールをダブルクリック


View Code
 1  //#region        
2 function tabin()
3 {
4 $.each($('#tab_Single tr:gt(0)'),function(){
5 $(this).children().eq(8).click(function(){
6 if($(this).find('input')!=null & $(this).children().attr("tagName")!='INPUT'){
7 $(this).html('<input type=\'text\' value=\''+$(this).html()+'\' onfocusout=\'tabout(this);\' style=\'width:'+($(this).width()-10)+'px;text-align:center\'/>');
8 $(this).find('input').focus();// bug
9 }
10 });
11 });
12 }
13 //#endregion
14
15
16 //#region
17 function tabout(obj){
18 var reg = new RegExp("^([+-]?)\\d*\\.?\\d+$");
19 if($(obj).attr("tagName")=='INPUT')
20 {
21 var val=$(obj).val();
22 if(!reg.test(val))
23 {
24 val=0;
25 }
26 $(obj).parent().html(val);
27 }
28 }
29 //#endregion

--JQuery2DOM DOM2JQuery 


View Code
 1 1、DOM   jQuery   
2 Dom $() jQuery 。
3
4 :$(document.getElementById("msg"))
5 jQuery , jQuery 。
6
7 2、jQuery DOM
8 jQuery 。 jQuery Dom , 。
9 : $("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5]
10
11 Dom , Dom , jQuery 。
12
13
14 $("#msg").html();
15 $("#msg")[0].innerHTML;
16 $("#msg").eq(0)[0].innerHTML;
17 $("#msg").get(0).innerHTML;

--Json使用


View Code
 1 $.getJSON("url,{url  1:url  1 ,url  2:url  2 ,...},            ")
2
3 url:"GISQueryControl.aspx"
4
5 data:{action:'ClickQuery',pegcode:strPegCode,ShowDiv:strDivId}
6
7 function OnClickQueryCallBack(data,textStatus)
8 {
9 if(textStatus=="success")
10 {
11 var htmlStr ;
12 if(typeof(data)!="undefined"&&data!=null&&data.length>0)
13 {
14 htmlStr="<table>";
15 for(i=0;i<data.length;i++)
16 {
17 htmlStr+= "<tr class=\"TR_BG\"><td>"+data[i].PegPipCode+"</td></tr>";
18 }
19 htmlStr += "</table></div>";
20 document.getElementById("TipdivCtrl").innerHTML = htmlStr;
21 }
22 }
23 }
24
25
26
27 :$.getJSON
28 {XX:xx,YY:yy,ZZ:zz}
29
30
31 string XX=Request[XX].ToString();
32 string YY=Request[YY].ToString();
33 string ZZ=Request[ZZ].ToString();
34
35
36 content="....";
37
38 content:
39 1. ( )
40 content="{AA:aa,BB:bb,CC:cc}";
41 2. ( )
42 content="[{AA:aa,BB:bb},{AA:cc,BB:dd}]";
43 Response.Write(content);
44
45 :CallBack(data,textStatus)
46 1.
47 var AA=data.AA;
48 var BB=data.BB;
49 var CC=data.CC;
50 2.
51 var AA="";
52 var BB="";
53 for(i=0;i<data.length;i++)
54 {
55 AA+=data[i].AA;
56 BB+=data[i].BB;
57 }
58
59 e.g. Json
60 :data.length=1
61 {ShowDivID:'divTipContent',PegCode:'1+700',MapX:'186',MapY:'89',PegPipCode:'1+700(CY-2)',LastDate:'2010-03-03',LastData:'5.864',BaseData:'',PipeCode:'CY-2',MPCD:'2006'}
62
63 :data.length=2
64 [
65 {ShowDivID:'divTipContent',PegCode:'1+700',MapX:'186',MapY:'89',PegPipCode:'1+700(CY-1)',LastDate:'2010-03-03',LastData:'6.923',BaseData:'',PipeCode:'CY-1',MPCD:'2005'},
66 {ShowDivID:'divTipContent',PegCode:'1+700',MapX:'186',MapY:'89',PegPipCode:'1+700(CY-2)',LastDate:'2010-03-03',LastData:'5.864',BaseData:'',PipeCode:'CY-2',MPCD:'2006'}
67 ]
68
69 :data.length=5
70 [
71 {ShowDivID:'divTipContent',PegCode:'1+700',MapX:'186',MapY:'89',PegPipCode:'1+700(CY-1)',LastDate:'2010-03-03',LastData:'6.923',BaseData:'',PipeCode:'CY-1',MPCD:'2005'},
72 {ShowDivID:'divTipContent',PegCode:'1+700',MapX:'186',MapY:'89',PegPipCode:'1+700(CY-2)',LastDate:'2010-03-03',LastData:'5.864',BaseData:'',PipeCode:'CY-2',MPCD:'2006'},
73 {ShowDivID:'divTipContent',PegCode:'2+350',MapX:'218',MapY:'130',PegPipCode:'2+350(CY-1)',LastDate:'2010-03-03',LastData:'6.582',BaseData:'',PipeCode:'CY-1',MPCD:'2009'},
74 {ShowDivID:'divTipContent',PegCode:'2+350',MapX:'218',MapY:'130',PegPipCode:'2+350(CY-2)',LastDate:'2010-03-03',LastData:'5.606',BaseData:'',PipeCode:'CY-2',MPCD:'2010'},
75 {ShowDivID:'divTipContent',PegCode:'2+350',MapX:'218',MapY:'130',PegPipCode:'2+350(CY-3)',LastDate:'2010-03-03',LastData:'4.824',BaseData:'',PipeCode:'CY-3',MPCD:'2011'}
76 ]

--Jqueryの一般的な方法


View Code
1.Window.onload  JQuery  
$(document).ready(function(){
//The Code!
})
:
$(function(){
//The Code!
})
2. Css
$(function(){
$(“a.alink”).mouseover(function(){
this.addClass(“over”); //
}).mouseout(function(){
this.removeClass(“over”); //
})
})
3.
$funciotn(){
$(a.alink).click(function(){
This.toggleClass(“highline”); // , ,
})
}
4.
$(".mytable tr:even").addClass("tr1");
5.
: $("p ").wrap(“<div class=’aa’></div >”);
:<p> </p>
: <div class=’aa’><p> </p></div >
6. 、
var sString = $(“p:frist”).text(); // P
$(“p:last”).html(sString); // P , Html , Html
7.
$(“img.eq(1)”).clone().appendTo($(“p”)); // P
8.
$(“img”)
.bind (“click”,fnMyfun1=function(){ // 1
$(“#show”).append(“ 1”); // id show
})
.bind (“click”,fnMyfun2=function(){// 2
$(“#show”).append(“ 2”);
})
.bind (“click”,fnMyfun3=function(){// 3
$(“#show”).append(“ 3”);
}) //
9.
$(“input(type=button)”).click(function(){
$(“img”).unbind(“click”,” fnMyfun1”); // fnMyfun1
})
10.JQuery ――
$(“img”).hide();
$(“img”).hide(3000); //
$(“img”).show ();
$(“img”).show (3000);
:fadeIn() fadeout() slideUp() slideDown()

--JS value値によるliのソート


View Code
 1 <html>
2 <head>
3 <title> span value , li </title>
4 <script type="text/javascript">
5 //
6 function sortList(){
7 var lis=document.getElementById("oList").childNodes;
8 for (var i = 0; i < lis.length - 1; i++) {
9
10 for (var j = 0; j < lis.length - 1; j++) {
11
12 if(parseInt(lis[j].childNodes[0].value)>parseInt(lis[j+1].childNodes[0].value)){
13
14 lis[j].swapNode(lis[j+1]); //
15 lis=document.getElementById("oList").childNodes; //
16
17 }
18 }
19 }
20 }
21 </script>
22 </head>
23
24 <body>
25 <ul id="oList">
26 <li><span value="3"> </span></li>
27 <li><span value="8"> </span></li>
28 <li><span value="2"> </span></li>
29 <li><span value="5"> </span></li>
30 <li><span value="7"> </span></li>
31 <li><span value="9"> </span></li>
32 <li><span value="4"> </span></li>
33 <li><span value="6"> </span></li>
34 <li><span value="1"> </span></li>
35 <li><span value="10"> </span></li>
36 </ul>
37 <INPUT TYPE = button VALUE = "Swap List" onclick = "sortList()">
38 </body>
39 </html>

--JSはサービス側にデータを提出する


View Code
 1 1.    (    )--- Ajax  
2
3 <!-- -->
4
5 $.ajax({
6
7 type: "POST",
8
9 url: "../Control/Ajax_Excel.aspx",
10
11 data: {htmlStr:escape(tempStr)},
12
13 success: function(data)
14
15 {
16
17 }
18
19 });
20
21 2. ( )---Form
22
23 <!-- -->
24
25 <form id="form1" runat="server" method="post">
26
27 <asp:HiddenField ID="hid_tempStr" runat="server" /> <!-- HTML -->
28
29 </form>
30
31 <script type="text/javascript">
32
33 $(function () {
34
35 $('#btn_Excel').click(function () {
36
37 $('#hid_tempStr').val(‘ Html ’);
38
39 document.form1.action="../Control/Ajax_Excel.aspx";//
40
41 document.form1.submit();
42
43 document.form1.action="../StaAnalyse/ProjManage.aspx";// , action ,
44
45 });
46
47 });
48
49 </script>
50
51 <!--Web.config-->
52
53 <system.web>
54
55 <httpRuntime requestValidationMode="2.0" /> <!-- -->
56
57 <pages validateRequest="false"/> <!-- -->
58
59 </system.web>
60
61 <!-- -->
62
63 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax_Excel.aspx.cs" Inherits="Control_Ajax_Excel" EnableViewStateMac="false" %> <!-- -->
64
65 <!-- -->
66
67
68 public partial class Control_Ajax_Excel : System.Web.UI.Page
69
70 {
71
72 protected void Page_Load(object sender, EventArgs e)
73
74 {
75
76 string HtmlStr=Request.Params["hid_tempStr"]==null?string.Empty:Server.UrlDecode(Request.Params["hid_tempStr"].ToString());
77
78 ......
79
80 }
81
82 }

--JS Excelのエクスポート


View Code
 1 tempStr html table,  :<TABLE id=tabReport class=tb_Content border=1>......</TABLE>
2
3 $('#btn_Excel').click(function () {
4
5 var newWin = window.open();
6 newWin.document.write(tempStr);
7 newWin.document.close();
8 newWin.document.execCommand('saveas',true,' .xls');
9 newWin.window.close();
10
11
12 , , 。 0px iframe 。
13
14 $('#btn_Excel').click(function () {
15 ifra_Excel.document.body.innerHTML=tempStr;
16 ifra_Excel.document.write(tempStr);
17 ifra_Excel.document.execCommand('saveas',true,' .xls');
18
19
20 <iframe id="ifra_Excel" style="width:0px;height:0px;border:0px"></iframe>

--JS連結作成列同一値セル


View Code
 1 mergeRowsByColumn(document.getElementById('tabReport'),23);        //   ID='tabReport',      =23 
2
3 function mergeRowsByColumn(tableObj,columnIndex)
4 {
5 for(var i=0;i<tableObj.rows.length-1;i++)
6 {
7 var td1=tableObj.rows[i].cells[columnIndex];
8 for(var j=i+1;j<tableObj.rows.length;j++)
9 {
10 var td2=tableObj.rows[j].cells[columnIndex];
11 if(td1.innerHTML==td2.innerHTML)
12 {
13 td1.rowSpan++;
14 tableObj.rows[j].deleteCell(columnIndex);
15 i++;
16 }
17 else
18 {
19 break;
20 }
21 }
22 }
23 }

--算術演算計算は2桁の小数を保持する


View Code
1  function cale()
2 {
3 var EstimatedRatio=$('#tb_EstimatedRatio').val();
4 var EstimatedMonney=$('#tb_EstimatedMonney').val();
5 if(EstimatedRatio.replace(/(^\s*)|(\s*$)/g, "")=='') EstimatedRatio=0;
6 if(EstimatedMonney.replace(/(^\s*)|(\s*$)/g, "")=='') EstimatedMonney=0;
7 $('#tb_EstimatedCost').val((parseFloat(EstimatedRatio)*parseFloat(EstimatedMonney)).toFixed(2));
8 }

--JS eval 


View Code
 1   :       js       
2
3 e.g.
4
5
6
7 data Json: [{Key:1,TypeName:AA},{Key:2,TypeName:AA},{Key:3,TypeName:BB}]
8
9 // Json col
10 function getSingles(data,col)
11 {
12 var tmp = "";
13 var arr=[];
14 var single="data[i]."+col;
15 for(var i=0;i<data.length;i++)
16 {
17 if(i==0)
18 {
19 tmp = eval(single);
20 arr.push(eval(single));
21 }
22 else
23 {
24 if(tmp!=eval(single))
25 {
26 tmp = eval(single);
27 arr.push(eval(single));
28 }
29 }
30 }
31 return arr;
32 }
33
34
35
36 getSingles(data,"TypeName");
37
38
39
40 [AA,BB]

--Json2Str Str2Json 


View Code
 1 1、Str Json
2 var str="[{key:1,value:1},{key:2,value:2}]";
3 state = eval(str);
4 for(i=0;i<state.length;i++)
5 {
6 state[i].value;
7 }
8
9 2、Json Str
10 function json2Str(o) {
11 var arr = [];
12 var fmt = function(s) {
13 if (typeof s == 'object' && s != null) return json2str(s);
14 return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;
15 }
16 for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));
17 return '{' + arr.join(',') + '}';
18 }

--JSマウス位置の取得


View Code
 1 //       
2 function mousePosition(ev)
3 //#region
4 {
5 if(ev.pageX || ev.pageY)
6 {
7 return {x:ev.pageX, y:ev.pageY};
8 }
9 return {x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,y:ev.clientY + document.body.scrollTop - document.body.clientTop};
10 }
11 //#endregion
12
13 :
14 var ev = ev || window.event;
15 var mousePos = mousePosition(ev);
16 alert(mousePos.x+mousePos.y);

--JS変更background


View Code
1 function changeBgImage(obj){ 
2 obj.style.cssText="background:url('2.gif') no-repeat 2 3";
3 }

--JS文字列接合効率


View Code
 1 <script>   
2 function code1(){
3 var str = '';
4 var startDate = new Date();
5 for(i=0;i<50000;i++){
6 str+='abc';
7 }
8 var endDate = new Date();
9 alert(endDate-startDate);
10 }
11
12 function code2(){
13 var startDate = new Date();
14 var arr = [];
15 for(i=0;i<50000;i++){
16 arr.push('abc');
17 }
18 var str = arr.join('');
19 var endDate = new Date();
20 alert(endDate-startDate);
21 }
22 </script>
23 <BODY>
24 <script>
25 code1();
26 code2();
27 </script>
28 </BODY>
29 IE6 FireFox :
30 CODE1 CODE2
31 IE6 1390 172
32 FF 4 7

--JS制御textareaのmaxLength


View Code
 1 textarea     maxLength  ,       ,        ,
2
3 textarea maxLength, maxLength textare , , maxLength , textarea ,
4
5 textarea maxLength , , maxLength , , input maxLength , , 。
6
7 <html>
8
9 <head>
10
11 <title></title>
12 <script type="text/javascript">
13
14 var textarea_maxlen = {
15 isMax : function (){
16 var textarea =
17 document.getElementById("area");
18 var max_length = textarea.maxLength;
19 if(textarea.value.length > max_length){
20 textarea.value =
21 textarea.value.substring(0, max_length);
22 }
23 },
24 disabledRightMouse : function (){
25 document.oncontextmenu =
26 function (){ return false; }
27 },
28 enabledRightMouse : function (){
29 document.oncontextmenu = null;
30 }
31 };
32 </script>
33 </head>
34
35 <body>
36 <textarea id="area" maxLength="10"
37 onkeyup="textarea_maxlen.isMax()"
38 onfocus="textarea_maxlen.disabledRightMouse()"
39 onblur="textarea_maxlen.enabledRightMouse()"
40 rows="20" cols="100">
41 </textarea>
42 </body>
43
44 </html>

--JS DateDiff


View Code
 1 function dateDiff(interval, date1, date2)
2 {
3 var objInterval = {'D' : 1000 * 60 * 60 * 24, 'H' : 1000 * 60 * 60, 'M' : 1000 * 60, 'S' : 1000, 'T' : 1};
4 interval = interval.toUpperCase();
5 var dt1 = Date.parse(date1.replace(/-/g, '/'));
6 var dt2 = Date.parse(date2.replace(/-/g, '/'));
7 try
8 {
9 return Math.round((dt2 - dt1) / eval('(objInterval.' + interval + ')'));
10 }
11 catch (e)
12 {
13 return e.message;
14 }
15 }

--JS横スクロール広告


View Code
 1 <HTML><HEAD><TITLE>     </TITLE>
2 <META http-equiv=Content-Type content="text/html; charset=gb2312">
3 <META content="MSHTML 6.00.2800.1264" name=GENERATOR>
4 <link href="css/css.css" rel="stylesheet" type="text/css">
5 </HEAD>
6 <BODY leftMargin=0 topMargin=2 marginheight="0" marginwidth="0">
7 <CENTER>
8 <TABLE
9 style="BORDER-RIGHT: #666666 1px solid; BORDER-TOP: #666666 1px solid; BORDER-LEFT: #666666 1px solid; BORDER-BOTTOM: #666666 1px solid"
10 cellSpacing=0 cellPadding=0 width=750 align=center border=0>
11 <TBODY>
12 <TR>
13 <TD>
14 <DIV id=demo style="OVERFLOW: hidden; WIDTH: 100%; COLOR: #ffffff">
15 <TABLE cellSpacing=0 cellPadding=0 align=left border=0 cellspace="0">
16 <TBODY>
17 <TR>
18 <TD id=demo1 vAlign=top><table width="1710" height="116" border="0" cellpadding="0" cellspacing="0">
19 <tr>
20 <td width="171" background="images/pic_bg.jpg"><div align="center">1</div></td>
21 <td width="171" background="images/pic_bg.jpg"><div align="center">
22 <p>2</p>
23 </div></td>
24 <td width="171" background="images/pic_bg.jpg"><div align="center">3</div></td>
25 <td width="171" background="images/pic_bg.jpg"><div align="center">4</div></td>
26 <td width="171" background="images/pic_bg.jpg"><div align="center">5</div></td>
27 <td width="171" background="images/pic_bg.jpg"><div align="center">6</div></td>
28 <td width="171" background="images/pic_bg.jpg"><div align="center">7</div></td>
29 <td width="171" background="images/pic_bg.jpg"><div align="center">8</div></td>
30 <td width="171" background="images/pic_bg.jpg"><div align="center">9</div></td>
31 <td width="171" background="images/pic_bg.jpg"><div align="center">10</div></td>
32 </tr>
33 </table></TD>
34 <TD id=demo2 vAlign=top>&nbsp;</TD></TR></TBODY></TABLE></DIV>
35 <SCRIPT>
36 var speed3=25//
37 demo2.innerHTML=demo1.innerHTML
38 function Marquee(){
39 if(demo2.offsetWidth-demo.scrollLeft<=0)
40 demo.scrollLeft-=demo1.offsetWidth
41 else{
42 demo.scrollLeft++
43 }
44 }
45 var MyMar=setInterval(Marquee,speed3)
46 demo.onmouseover=function() {clearInterval(MyMar)}
47 demo.onmouseout=function() {MyMar=setInterval(Marquee,speed3)}
48 </SCRIPT>
49 </TD></TR></TBODY></TABLE></TD></TR></TABLE>
50 </CENTER>
51 </BODY></HTML>

--JS遍歴checkbox getElementsByTagName


View Code
 1  var chksStr="";
2 var inputs=document.getElementsByTagName("input");
3 var chkboxs;
4 for(var i=0;i<inputs.length;i++)
5 {
6 if(inputs[i].type == "checkbox")
7 {
8 if(inputs[i].checked)
9 {
10 chksStr+=","+inputs[i].id.substr(3,inputs[i].id.length);
11 }
12 }
13 }
14 chksStr =chksStr.substr(1,chksStr.length);
15 alert(chksStr);

--JS検証コントロール入力正当性


View Code
 1 js  :
2 function revMobilePhone(obj)
3 {
4 var tt=/^\d{11}|\d{3,4}-\d{7,8}/;
5 if(!tt.exec(obj))
6 {
7 alert(" ");
8 }
9 }
10
11 <asp:TemplateField HeaderText=" ?">
12 <EditItemTemplate>
13 <input id="tbMobilePhone" value='<%# Bind("MobilePhone") %>' runat="server" type="text" onblur="revMobilePhone(this.value)" />
14 </EditItemTemplate>
15 <ControlStyle Width="120px" />
16 <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="10px" Height="25px" />
17 <ItemTemplate>
18 <asp:Label ID="lbMobilePhone" runat="server" Text='<%# Bind("MobilePhone") %>' Font-Size="13px"></asp:Label>
19 </ItemTemplate></asp:TemplateField>
20
21
22 protected void gvShow_RowUpdating(object sender, GridViewUpdateEventArgs e)
23 {
24 ...
25 string mobilephone = ((HtmlInputText)(gvShow.Rows[e.RowIndex].Cells[0].FindControl("tbMobilePhone"))).Value.ToString().Trim();
26 ...
27 }

--JS QueryString


View Code
 1 function QueryString()
2 {
3 //
4 var name,value,i;
5 var str=location.href;// URL
6 var num=str.indexOf("?")
7 str=str.substr(num+1);// “?”
8 var arrtmp=str.split("&");//
9 for(i=0;i < arrtmp.length;i++)
10 {
11 num=arrtmp[i].indexOf("=");
12 if(num>0)
13 {
14 name=arrtmp[i].substring(0,num);//
15 value=arrtmp[i].substr(num+1);//
16 this[name]=value;//
17 }
18 }
19 }
20
21 :
22 var abc = new QueryString();
23 alert(abc.id);//id

--JS妙用iframe内容に応じて高さを自動調整


View Code
 1 //    
2
3 var GLOB_CONST_extraHeight_IE = 4; //using default value 4 of IE
4 var GLOB_CONST_extraHeight_NOIE = 16 ; //using default value 16 of FF
5 function autosize() {
6 try {
7 var iframe = parent.document.getElementsByTagName('iframe');
8 var len = iframe.length;
9 if (len <= 0) {
10 return;
11 }
12 var i;
13 if (iframe[0].contentDocument) { //for mozilla, firefox
14 for (i = 0; i < len; i ++) {
15 if (iframe[i].contentDocument == document) {
16 iframe[i].style.height=document.body.offsetHeight +GLOB_CONST_extraHeight_NOIE;
17 return;
18 }
19 }
20 }
21 else { // for IE
22 iframe = parent.document.frames;
23 len = iframe.length;
24 if (len <= 0) {
25 return;
26 }
27 for (i = 0; i < len; i ++) {
28 if (iframe[i].document == document) {
29 iframe[i].frameElement.style.height=document.body.scrollHeight+ GLOB_CONST_extraHeight_IE;
30 return;
31 }
32 }
33 }
34 }catch(err) {
35 alert(err.message);
36 }
37 }
38
39 // body onLoad="autosize()"

--JSピクチャプリロードコード表示loading


View Code
 1 <html>
2 <head>
3 <style type="text/css">
4 div{border:#aaaaaa 3px solid;width:200px;padding:2px;margin:2px 9px;font-size:12px;line-height:22px;color:#999999;}
5 .ipt1{width:160px;font-size:12px;color:#1F6478;border:#999999 1px solid;margin-left:9px;}
6 .ipt2{border:#999999 1px solid;margin-left:6px;color:#666666}
7 p{margin:0px;padding:0px;background-image:url(http://www.codefans.net/jscss/demoimg/loading.gif);background-position:center;background-repeat:no-repeat;width:200px;height:200px;text-align:center;font-size:12px;color:#999999;line-height:26px;}
8 </style>
9 <script language="javascript" type="text/javascript">
10 function preloadimg(url,obj,ipt){
11 var img=new Image();
12 obj.innerHTML="<p> ...</p>";
13 img.onload=function(){obj.innerHTML="";obj.style.width=String(img.width)+"px";ipt.style.width=String(img.width-40)+"px";obj.appendChild(img);};
14 img.onerror=function(){obj.innerHTML=" !"};
15 img.src=url; //img.src img.onload , IE
16 }
17 function show(){
18 var div=document.getElementsByTagName("div")[0];
19 var input=document.getElementsByTagName("input");
20 preloadimg("http://www.codefans.net/jscss/demoimg/wall8.jpg",div,input[0]);
21 input[0].onclick=function(){this.value=""};
22 input[1].onclick=function(){preloadimg(input[0].value,div,input[0]);}
23 }
24 window.onload=show;
25 </script>
26 <title>JavaScript , loading</title>
27 </head>
28 <body>
29 <div></div>
30 <br />
31 <input type="text" value=" " class="ipt1"/><input type="button" value=" " class="ipt2"/>
32 </body>
33 </html>

--JSにおけるsubstrとsubstringの違い


View Code
1 String.substr(N1,N2)                (N1)      (N2)    ;
2 String.substring(N1,N2) , N1,N2 , , , 。

--空振り判定


View Code
1 if(typeof(obj)!="undefined"&&obj!=null)
2 {
3 var aa=obj;
4 ...
5 }

--右ボタンを隠す


View Code
 1 <script type="text/javascript">
2 function document.oncontextmenu() {
3 return false;
4 }
5 function nocontextmenu() {
6 if (document.all) {
7 event.cancelBubble = true;
8 event.returnvalue = false;
9 return false;
10 }
11 }
12 </script>
13 <body onload="document.oncontextmenu();">

--iframeのコンテンツを取得


View Code
1 document.frames['framX'].document.body.innerHTML

--JS中国語urlパラメータの処理


View Code
1 window.location = encodeURI("FrmSearch.aspx?key=    ");

--CSSの制御


View Code
1 document.getElementById('ServiceCnt').style.cssText='margin-top:15px;margin-left:15px;'

--JSフィルタスペースTrim


View Code
1 function trim(str)
2 {
3 return (str + '').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
4 }

--JSテキストボックス自動フィルタスペース


View Code
1 <asp:TextBox ID="searchMobilePhone" runat="server" Width="80px" Text="" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"></asp:TextBox>

--JSでとても使いやすいディスプレー


View Code
1 style='display:<%Response.Write((UserType=="  ")?"inline":"none");%>'

--JSシールド右ボタン


View Code
 1  <script type="text/javascript">
2 function document.oncontextmenu() {
3 return false;
4 }
5 function nocontextmenu() {
6 if (document.all) {
7 event.cancelBubble = true;
8 event.returnvalue = false;
9 return false;
10 }
11 }
12 </script>
13 <body onload="document.oncontextmenu();">

--window.onloadの呼び出しの書き方


View Code
1 function bbb() 
2 {
3 aaa();
4 }
5 window.onload=bbb;

--JS時間


View Code
 1 var now= new Date();
2 var month = now.getMonth()+1;
3 var day = now.getDate();
4 var hour = now.getHours();
5 var min = now.getMinutes();
6 if(month<10){month="0"+(now.getMonth()+1);}
7 if(day<10){day="0"+now.getDate();}
8 if(hour<10){hour="0"+now.getHours();}
9 if(min<10){min="0"+now.getMinutes();}
10 var nowTim = now.getFullYear()+"-"+month+"-"+day+" "+hour+":"+min+":00";

--JSウィンドウ座標


View Code