您的位置:首页 > Web前端 > JavaScript

JavaScript 学习手记

2006-02-14 22:55 459 查看
JavaScript
 1.基本控件的使用

 

控件名.value
控件名.value
控件名[i].checked    .value 
for each ob in控件名
   if ob.checked then
      window.alert ob.value
next
控件名.checked    .value
Select 1Select 3Select 2Select 1Select 2Select 3Select 4Select 1Select 2Select 3Select 4
 
   单行         多行         多选
添加选项
ExpList.add(new Option("New Option","3"));
删除选项
ExpList.remove(ExpList.selectedIndex);
设置当前选项位置
ExpList.selectedIndex=ExpList.length-1;
循环整个选项
并判断是否被选择
for(i=0;i<ExpList.options.length;i++) {
  if(ExpList.options[i].selected){
     //ExpList.options[i].text;
     //ExpList.options[i].value;
  }
}
单个选项的值
ExpList.options[i].text;
ExpList.options[i].value;
<span id="SomePlace1"></span>
<div id="SomePlace1"></div>
重新设计包含的html
SomePlace1.innerHTML="任意html字符串"
让该空间的内容消失
SomePlace1.style.display="none";
让该空间的内容显示
SomePlace1.style.display="block";
鼠标滑过出现提示title="Help"
<input type="hidden" name="MyValueName" value="123">
控件名.value
跟随事件Event(声明方式特殊)<div id=hello1 style=position:absolute>太过分了!吃饭不叫我</div>
<SCRIPT for=document EVENT=onmousemove>
document_onmousemove();
function document_onmousemove() {
  hello1.style.left=event.x+10;
  hello1.style.top=event.y+10;
}
</SCRIPT>
<返回>

2.让TextArea自动换行

  使用TextArea的Wrap属性
 
Wrap may be set to one of the following values:

OFF - Default, lines are not wrapped.

PHYSICAL - Wrap lines and place new line characters where the line wraps.

VIRTUAL - Wrap lines on the screen, but receive them as one line.

ASP中手动换行用: replace(rs("A"),"</br>", VBCRLF)
str=request.querystring("text1")
str=Replace(str, Chr(32), " ")
'把空格换成 标志
str=Replace(str, vbCrLf, "<br>")
'把回车换行符换成<br>标志
调出时再转过来就好了

<返回>

3.让TextArea支持Table键
<SCRIPT LANGUAGE="JavaScript">
<!--
function testTab()
{
   var sel = document.selection.createRange();
   var mytext= sel.text;
   var i,j,k;
   if (event.shiftKey && event.keyCode == 9)
   {
      arr=mytext.split(String.fromCharCode(13,10))
      mytext=""

      for(k=0;k<arr.length;k++)
      {
         for (j=1; j<=4;j++)
         {
            if(arr[k].substr(0,1)=="/u0020")
            {
               arr[k]=arr[k].slice(1)
            }
         }
         mytext += arr[k] + ((k==(arr.length-1))? "" : String.fromCharCode(13,10));
      }
      with(sel){
         sel.text = mytext;
         collapse(true)
         moveEnd("character",0)
         moveStart("character",(mytext.length ) * -1)
         select()
      }

      window.event.cancelBubble = true;
      event.returnValue = false;
      return;
   }
   if (event.keyCode == 9)
   {
      arr=mytext.split(String.fromCharCode(13,10))
      mytext=""
      for(j=0;j<arr.length;j++)
      {
         mytext += "/u0020/u0020/u0020/u0020" + arr[j] + ((j==(arr.length-1))? "" : String.fromCharCode(13,10));
      }
      with(sel){
         sel.text = mytext;
         collapse(true)
         moveEnd("character",0)
         moveStart("character",(mytext.length -4) * -1)
         select()
      }

      window.event.cancelBubble = true;
      event.returnValue = false;
      return;
   }
}
//-->
</SCRIPT>

<返回>

4.复制数据到剪贴板

 JM_cc(txt)

 window.clipboardData.setData("Text", txt);
 global.focus();
 document.execCommand('Paste');
 window.clipboardData.setData("Text", old);

<返回>

5.得到当前选中的文本


var sel = document.selection.createRange();
var mytext= sel.text;  //当前选中的文本

var e = event.srcElement;  //设置文本为选中
var r =e.createTextRange();
r.moveStart('character',e.value.length);
r.collapse(true);
r.select();

<返回>

6.客户端脚本的基本对象
 

navigator

screen

window

history

location

frames[]; Frame

document

anchors[]; links[]; Link

applets[]

embeds[]

forms[]; Form

Button

Checkbox

elements[]; Element

Hidden

Password

Radio

Reset

Select

options[]; Option

Submit

Text

Textarea

images[]; Image

more >>>

浏览器对象
屏幕对象
窗口对象
 历史对象
 地址对象
 框架对象
 文档对象
  连接对象
  Java小程序对象
  插件对象
  表单对象
   按钮对象
   复选框对象
   表单元素对象
   隐藏对象
   密码输入区对象
   单选域对象
   重置按钮对象
   选择区(下拉菜单、列表)对象
    选择项对象
   提交按钮对象
   文本框对象
   多行文本输入区对象
  图片对象
<返回>

7.保护自己编写的HTML和脚本的方法
  (1). oncontextmenu="window.event.returnValue=false" 将彻底屏蔽鼠标右键
    <table border oncontextmenu=return(false)><td>no</table> 可用于Table
  (2). <body onselectstart="return false"> 取消选取、防止复制
  (3). onpaste="return false" 不准粘贴
  (4). oncopy="return false;" oncut="return false;" 防止复制
  (5). 防止被人frame
      <SCRIPT LANGUAGE=JAVASCRIPT><!--
         if (top.location != self.location)top.location=self.location;
       // -->
      </SCRIPT>
  (6). 永远都会带着框架
     <script language="JavaScript"><!--
        if (window == top)top.location.href = "frames.htm"; //frames.htm为框架网页
     // --></script>
  (7).网页将不能被另存为
     <noscript><iframe src=*.html></iframe></noscript>

<返回>

8.IE地址栏前换成自己的图标
 <link rel="Shortcut Icon" href="favicon.ico"> _fcksavedurl=""favicon.ico">"

<返回>

9.可以在收藏夹中显示出你的图标

 <link rel="Bookmark" href="favicon.ico"> _fcksavedurl=""favicon.ico">"

<返回>

10.关闭输入法

 <input style="ime-mode:disabled">

<返回>

11.直接查看源代码
 
 <input type=button value=查看网页源代码 onclick="window.location = 'view-source:'+ 'http://www.csdn.net/'">

<返回>

12.在Javascript中定义一个对象(属性,方法)

function pasta(grain, width, hasEgg) {
    this.grain = grain;
    this.width = width;
    this.hasEgg = hasEgg;
    this.toString = pastaToString;
}

function pastaToString() {
    return "Grain: " + this.grain + "/n" + "Width: " + this.width + "/n" + "Egg?: " + Boolean(this.hasEgg);
}

var P1=new pasta(3,3,false);

<返回>

13. 取得控件的绝对位置

//Javascript
<script language="Javascript">
function getIE(e){
   var t=e.offsetTop;
   var l=e.offsetLeft;
   while(e=e.offsetParent){
      t+=e.offsetTop;
      l+=e.offsetLeft;
   }
   alert("top="+t+"/nleft="+l);
}
</script>

<返回>

14. 光标是停在文本框文字的最后

<script language="javascript">
function cc()
{
   var e = event.srcElement;
   var r =e.createTextRange();
   r.moveStart('character',e.value.length);
   r.collapse(true);
   r.select();
}
</script>
<input type=text name=text1 value="123" onfocus="cc()">

<返回>

15. 判断上一页的来源

asp:
  request.servervariables("HTTP_REFERER")

javascript:
  document.referrer

<返回>

16. 最小化、最大化、关闭窗口

<object id=hh1 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
<param name="Command" value="Minimize"></object>
<object id=hh2 classid="clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11">
<param name="Command" value="Maximize"></object>
<OBJECT id=hh3 classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11">
<PARAM NAME="Command" VALUE="Close"></OBJECT>

<input type=button value=最小化 onclick=hh1.Click()>
<input type=button value=最大化 onclick=hh2.Click()>
<input type=button value=关闭 onclick=hh3.Click()>
本例适用于IE

<返回>

17. 检查一段字符串是否全由数字组成

<script language="Javascript"><!--
function checkNum(str){return str.match(//D/)==null}
// --></script>

<返回>

18. 获得一个窗口的大小

document.body.clientWidth,document.body.clientHeight

<返回>

19. 怎么判断是否是字符

if (/[^/x00-/xff]/g.test(s))
  alert("含有汉字");
else
  alert("全是字符");

<返回>

20. 检测某个网站的链接速度

把如下代码加入<body>区域中:
<script language=Javascript>
tim=1
setInterval("tim++",100)
b=1

var autourl=new Array()
autourl[1]="www.njcatv.net"
autourl[2]="javacool.3322.net"
autourl[3]="www.sina.com.cn"
autourl[4]="www.nuaa.edu.cn"
autourl[5]="www.cctv.com"

function butt(){
   document.write("<form name=autof>")
   for(var i=1;i<autourl.length;i++)
      document.write("<input type=text name=txt"+i+" size=10 value=测试中……> =》<input type=text name=url"+i+" size=40> =》<input type=button value=GO onclick=window.open(this.form.url"+i+".value)><br/>")
   document.write("<input type=submit value=刷新></form>")
}
butt()
function auto(url){
   document.forms[0]["url"+b].value=url
   if(tim>200)
   {
      document.forms[0]["txt"+b].value="链接超时"
   }
   else
   {
      document.forms[0]["txt"+b].value="时间"+tim/10+"秒"
   }
   b++
}
function run()
{
   for(var i=1;i<autourl.length;i++)
      document.write("<img src=http://"+autourl[i]+"/"+Math.random()+" width=1 height=1 onerror=auto('http://"+autourl[i]+"')>")
}
run()</script>

<返回>

21. 各种样式的光标

auto :标准光标
default :标准箭头
hand :手形光标
wait :等待光标
text :I形光标
vertical-text :水平I形光标
no-drop :不可拖动光标
not-allowed :无效光标
help :?帮助光标
all-scroll :三角方向标
move :移动标
crosshair :十字标
e-resize
n-resize
nw-resize
w-resize
s-resize
se-resize
sw-resize

<返回>

22.让TEXTAREA自适应文字的行数

<textarea rows=1 name=s1 cols=27 onpropertychange="this.style.posHeight=this.scrollHeight"></textarea>

<返回>

23. 日期减去天数等于第二个日期
<script language=Javascript>
function cc(dd,dadd)
{
//可以加上错误处理
   var a = new Date(dd)
   a = a.valueOf()
   a = a - dadd * 24 * 60 * 60 * 1000
   a = new Date(a)
   alert(a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日")
}
cc("12/23/2002",2)
</script>

<返回>

24. 选择了哪一个Radio

<HTML>
<script language="vbscript">
function checkme()
   for each ob in radio1
   if ob.checked then
      window.alert ob.value
   next
end function
</script>
<BODY>
<INPUT name="radio1" type="radio" value="style" checked>Style
<INPUT name="radio1" type="radio" value="barcode">Barcode
<INPUT type="button" value="check" onclick="checkme()">
</BODY></HTML>

<返回>

25.获得本页url的request.servervariables("")集合

Response.Write "<TABLE border=1><!-- Table Header --><TR><TD><B>Variables</B></TD><TD><B>Value</B></TD></TR>"
for each ob in Request.ServerVariables
   Response.Write "<TR><TD>"&ob&"</TD><TD>"&Request.ServerVariables(ob)&"</TD></TR>"
next
Response.Write "</TABLE>"

<返回>

26.ENTER键可以让光标移到下一个输入框

<input onkeydown="if(event.keyCode==13)event.keyCode=9">

<返回>

28.引用其他网页

<table width=100% border="0"><tr><td><script language="JavaScript" location="http://91down.7161.net" id="nd91down" src="http://91down.7161.net/js/new1-1.htm"></script></td><td><script language="JavaScript" location="http://91down.7161.net" id="nd91down" src="http://91down.7161.net/js/new1-2.htm"></script></td></tr></table>

<返回>

29.常用的正则表达式

匹配中文字符的正则表达式: [/u4e00-/u9fa5]
匹配双字节字符(包括汉字在内):[^/x00-/xff]
匹配空行的正则表达式:/n[/s| ]*/r
匹配HTML标记的正则表达式:/<(.*)>.*<///1>|<(.*) //>/
匹配首尾空格的正则表达式:(^/s*)|(/s*$)匹配Email地址的正则表达式:/w+([-+.]/w+)*@/w+([-.]/w+)*/./w+([-.]/w+)*
匹配网址URL的正则表达式:http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?

(1)应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)
        
    String.prototype.len=function(){return this.replace([^/x00-/xff]/g,"aa").length;}

(2)应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现
   String.prototype.trim = function()
   {
      return this.replace(/(^/s*)|(/s*$)/g, "");
   }
(3)应用:利用正则表达式分解和转换IP地址
   function IP2V(ip) //IP地址转换成对应数值
   {
      re=/(/d+)/.(/d+)/.(/d+)/.(/d+)/g //匹配IP地址的正则表达式
      if(re.test(ip))
      {
         return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
      }
      else
      {
         throw new Error("Not a valid IP address!")
      }
   }
(4)应用:从URL地址中提取文件名的javascript程序
   s="http://www.9499.net/page1.htm";
   s=s.replace(/(.*//){0,}([^/.]+).*/ig,"$2") ; //Page1.htm
(5)应用:利用正则表达式限制网页表单里的文本框输入内容
   用正则表达式限制只能输入中文:onkeyup="value=value.replace(/[^/u4E00-/u9FA5]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/u4E00-/u9FA5]/g,''))"
   用正则表达式限制只能输入全角字符: onkeyup="value=value.replace(/[^/uFF00-/uFFFF]/g,'')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/uFF00-/uFFFF]/g,''))"
   用正则表达式限制只能输入数字:onkeyup="value=value.replace(/[^/d]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"
   用正则表达式限制只能输入数字和英文:onkeyup="value=value.replace(/[/W]/g,'') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^/d]/g,''))"

<返回>

30.弹出来提示对话框
window.showModalDialog(url);

<返回>

31.取得查询字符串,然后就生成成对的数组
var argstr = window.top.location.search.substring(1,window.top.location.search.length);
var args = argstr.split('&');

<返回>

32.另类的onload函数
<SCRIPT FOR=window event=onload>
try
{
  Start();
}
catch (exception)
{
}
</script>

<返回>

33.取得IE的版本
var ieVer = parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf("MSIE ")+5, navigator.appVersion.length))
var isIE6 = ieVer >= 6.0

<返回>

34.提交表单
// aimForm 为表单名    aimPage为提交到的页

//提交表单到新建的网页
function SubmitFormToNewPage(aimForm,aimPage){
   aimForm.method="POST";
   aimForm.target="_blank";
   aimForm.action=aimPage;
   aimForm.submit();
}

//在本地提交表单
function SubmitFormToLocalPage(aimForm,aimPage){
   aimForm.method="POST";
   aimForm.target="_self";
   aimForm.action=aimPage;
   aimForm.submit();
}

<返回>

35.判断是否是整数
function IsNum(s)  //整数
{
   if(s=="null"||s=="undefined"||s.length<1)
      return false;
   if(isNaN(parseInt(s)))
      return false;
   else
   if((parseInt(s)+"").length!=s.length)
      return false;
   else
      return true;
}

function IsNumber(JudgeNum){  //判断大于0的数
   var JudgeStr=JudgeNum.toString();
   for (var i=0;i<JudgeStr.length;i++) {
      var oneChar=JudgeStr.charAt(i);

      if (oneChar<"0" || oneChar >"9"){
         return false;
      }
   }
   return true;
}

<返回>

36.链接css文件和js文件
<link rel="stylesheet" href="../css/style.css" _fcksavedurl=""../css/style.css"" type="text/css">
<script language="javascript" src="../includes/jslib.js" ></script>

<返回>

37.引用框架的内容
window.top.frames["mainFrame"].location.href=s;
在IFRAME标签中引用框架的内容
parent.frames["mainFrame"].location.href
在窗口中引用IFrame中的内容
window.top.frames["mainFrame"].confFrame.location.href

<返回>

38.打开没有最大化按钮的窗口
window.open("http://www.google.com","","width=250,height=220,scrollbars=no,resizable=no,center=yes");

<返回>

39.在页面上显示一个有边框的Frame
<fieldset style="width:500;height:100">
<legend>标题</legend>
具体内容
</fieldset>

<返回>

40.判断日期1是不是大于日期2

function IsDate1AfterThanDate2(year1,month1,day1,year2,month2,day2){
   var iFrom=Date.parse(month1+"-"+day1+"-"+year1);
   var iTo=Date.parse(month2+"-"+day2+"-"+year2);
   if(iFrom>iTo)
      return true;
   else
      return false;
}

function IsDate(year,month,day){
   if( (!IsNumber(year))||(year.length!=4))
      return false;
   if( (!IsNumber(month))||(month>12)||(month<1) )
      return false;
   if( (!IsNumber(day))||(day>31)||(day<1) )
      return false;

   var myDate=new Date();
      myDate.setFullYear(year,month-1,day);
   if (isNaN(myDate.getFullYear())){
      return false;
   }
   else{
      if( (myDate.getFullYear()!=year)||(myDate.getDate()!=day)||(myDate.getMonth()!=(month-1).toString()) )
         return false;
   }
      return true;
}

function IsNumber(JudgeNum){
   var JudgeStr=JudgeNum.toString();
   for (var i=0;i<JudgeStr.length;i++) {
      var oneChar=JudgeStr.charAt(i);

      if (oneChar<"0" || oneChar >"9"){
         return false;
      }
   }
   return true;
}

<返回>

41.常用的Javascript内建类的方法
 
对象
方法或属性
意义
例子
Array
length
表示数组大小,也可以通过该属性动态调整数组大小。设置可以不调整它直接扩大数组。
var theMonths = new Array(12);
theMonths[0] = "Jan";
theMonths[1] = "Feb";
theMonths[2] = "Mar";
theMonths[20] = "12";
concat
把两个数组合并
a = new Array(1,2,3);
b = new Array(4,5,6);
a = a. concat(b)
join
把数组变为字符串
   a = new Array(0,1,2,3,4);
   b = a.join("-");
Date
Date.parse(dateVal)
将日期转为数字,用于比较两个日期的大小。dateVal格式为month+day+year
iFrom=Date.parse(“10-1-2004”);
setFullYear (year,month-1,day)
用于判断3个字符串合起来是不是日期或者判断该天是不是存在。这里month从0开始,故和实际值差1
myDate.setFullYear(year,month-1,day);
if (isNaN(myDate.getFullYear())){
      return false;
}
else{
  if( (myDate.getFullYear()!=year)||
(myDate.getDate()!=day)||
(myDate.getMonth()!=(month-1) )
      return false; 
}
Date()
获得当前时间
d = new Date();                          
Global (全局类,引用方法可以不要带Global.)
isNaN
当从字符到日期转换失败,或者从字符到数字转换失败,都返回NaN。用isNaN可以判断返回值是不是NaN
 
parseInt
将字符串转换为整数,转换失败返回NaN或者尽量转换。所以用它来判断是不是数字,还要加上判断转化后长度是不是一样
parseInt("abc")     // 返回 NaN。
parseInt("12abc")   // 返回 12。
parseInt("12")   // 返回 12
parseFloat
转为实数
 
String
主要函数和Java或者C#一样
replace
替代某个字符。如果仅替代一个和C#一样,如果要替代全部某字符,就得用到了匹配串
  re=/#/g;
  str=str.replace(re,"<br>");

 
把#用<br>代替
split
将某个字符串按指定间隔符分割
var s = "The rain in Spain";
ss = s.split(" ");  //ss是一个数组
<返回>

42.如何在另一个窗体对原来窗体进行操作

  (1)对用window.open打开的新窗体,用window.opener来访问原来窗体的对象。例如重新加载页面 window.opener.location.reload();  可以通过window.opener.varName 来访问原变量。
  (2)对用showModalDialog打开的新窗体
     (主页面)   var returnvalue=window.showModalDialog('2.htm',this,"status=no; help=no; dialogWidth=330px; dialogHeight=305px;");  //第二个参数传入本窗体
     (子页面)   window.dialogArguments.varName 来访问原变量
                window.returnValue=***         来设定returnvalue的值
<返回>

43.层的隐藏与显示

只要设置style的display属性即可。比如<div style="display:none" id="MyDiv">隐藏的层</div>
(1)如果要显示它可以通过脚本来控制    window.document.getElementById("MyDiv").style.display = "";
(2)如果要隐藏它可以通过脚本来控制    window.document.getElementById("MyDiv").style.display = "none";

<返回>

44.禁止右键

<body oncontextmenu="return false">

<返回>

45.屏蔽页面中程序运行出错信息
 
window.onerror = function()
{
   return true;
}
try{
......
}
catch(e){}
<返回>
46.得到当前显示器的分辨率

window.srceen.width 得到屏幕的宽度
window.srceen.height 得到屏幕的高度
如果当前分辨率为800*600,window.srceen.width是800,window.srceen.height是600
<返回>

47.定时运行特定代码

setTimeout(Code,Timeout);
setInterval(Code,Timeout);
Code是一段字符串,里边是js代码,Timeout是时间间隔,单位是微秒
setTimeout是从现在算起多少微秒后运行该代码(只运行一次)
setInterval是每隔多少微秒运行一次代码

<返回>

48.得到本页网址

var Url = window.location.href;

<返回>

49.保存当前页面的内容

document.execCommand("SaveAs","","C://index.htm"); 
//execCommand实际上是一个功能强大的函数,一般的编辑器都是用其实现。详见 http://www.51js.com/viewthread.php?tid=13450&fpage=1&highlight=execCommand

<返回>

50.刷新当前页面

window.location.reload();
<返回>

51.获得当前日期

var d; d = new Date();
alert (d.getMonth() + 1); // 获取月份。
alert (d.getDate()); // 获取日。
alert (d.getYear()); // 获取年份。

<返回>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息