javascript常用技巧

1、〖打开〗命令的实现
[格式]:document.execCommand("open")
[说明]这跟VB等编程设计中的webbrowser控件中的命令有些相似,大家也可依此琢磨琢磨。
[举例]在<body></body>之间加入:
<a href="###" οnclick=document.execCommand("open")>打开</a>

2、〖使用 记事本 编辑〗命令的实现
[格式]:location.replace("view-source:"+location)
[说明]打开记事本,在记事本中显示该网页的源代码。
[举例]在<body></body>之间加入:
<a href="###" οnclick=location.replace("view-source:"+location)>使用 记事本编辑</a>

3、〖另存为〗命令的实现
[格式]:document.execCommand("saveAs")
[说明]将该网页保存到本地盘的其它目录!
[举例]在<body></body>之间加入:
<a href="###" οnclick=document.execCommand("saveAs")>另存为</a>

4、〖打印〗命令的实现
[格式]:document.execCommand("print")
[说明]当然,你必须装了打印机!
[举例]在<body></body>之间加入:
<a href="###" οnclick=document.execCommand("print")>打印</a>

5、〖关闭〗命令的实现
[格式]:window.close();return false
[说明]将关闭本窗口。
[举例]在<body></body>之间加入:
<a href="###" οnclick=window.close();return false)>关闭本窗口</a>

180.【编辑(E)】菜单中的命令的实现

〖全选〗命令的实现
[格式]:document.execCommand("selectAll")
[说明]将选种网页中的全部内容!
[举例]在<body></body>之间加入:
<a href="###" οnclick=document.execCommand("selectAll")>全选</a>

181.【查看(V)】菜单中的命令的实现

1、〖刷新〗命令的实现
[格式]:location.reload() 或 history.go(0)
[说明]浏览器重新打开本页。
[举例]在<body></body>之间加入:
<a href="###" οnclick=location.reload()>刷新</a>
或加入:
<a href="###" οnclick=history.go(0)>刷新</a>

2、〖源文件〗命令的实现
[格式]:location.replace("view-source:"+location)
[说明]查看该网页的源代码。
[举例]在<body></body>之间加入:
<a href="###" οnclick=location.replace("view-source:"+location)>查看源文件</a>

3、〖全屏显示〗命令的实现
[格式]:window.open(document.location, "url", "fullscreen")
[说明]全屏显示本页。
[举例]在<body></body>之间加入:
<a href="###" οnclick=window.open(document.location,"url","fullscreen")>全屏显示</a>

182.【收藏(A)】菜单中的命令的实现

1、〖添加到收藏夹〗命令的实现
[格式]:window.external.AddFavorite('url', '“网站名”)
[说明]将本页添加到收藏夹。
[举例]在<body></body>之间加入:
<a href="javascript:window.external.AddFavorite('http://oh.jilinfarm.com', '胡明新的个人主页')">添加到收

藏夹</a>

2、〖整理收藏夹〗命令的实现
[格式]:window.external.showBrowserUI("OrganizeFavorites",null)
[说明]打开整理收藏夹对话框。
[举例]在<body></body>之间加入:
<a href="###" οnclick=window.external.showBrowserUI("OrganizeFavorites",null)>整理收藏夹</a>

183.【工具(T)】菜单中的命令的实现

〖internet选项〗命令的实现
[格式]:window.external.showBrowserUI("PrivacySettings",null)
[说明]打开internet选项对话框。
[举例]在<body></body>之间加入:
<a href="###" οnclick=window.external.showBrowserUI("PrivacySettings",null)>internet选项</a>

184.【工具栏】中的命令的实现

1、〖前进〗命令的实现
[格式]history.go(1) 或 history.forward()
[说明]浏览器打开后一个页面。
[举例]在<body></body>之间加入:
<a href="###" οnclick=history.go(1)>前进</a>
或加入:
<a href="###" οnclick=history.forward()>前进</a>

2、〖后退〗命令的实现
[格式]:history.go(-1) 或 history.back()
[说明]浏览器返回上一个已浏览的页面。
[举例]在<body></body>之间加入:
<a href="###" οnclick=history.go(-1)>后退</a>
或加入:
<a href="###" οnclick=history.back()>后退</a>

3、〖刷新〗命令的实现
[格式]:document.reload() 或 history.go(0)
[说明]浏览器重新打开本页。
[举例]在<body></body>之间加入:
<a href="###" οnclick=location.reload()>刷新</a>
或加入:
<a href="###" οnclick=history.go(0)>刷新</a>

185.其它命令的实现
〖定时关闭本窗口〗命令的实现
[格式]:settimeout(window.close(),关闭的时间)
[说明]将关闭本窗口。
[举例]在<body></body>之间加入:
<a href="###" οnclick=settimeout(window.close(),3000)>3秒关闭本窗口</a>


【附】为了方便读者,下面将列出所有实例代码,你可以把它们放到一个html文件中,然后预览效果。
<a href="###" οnclick=document.execCommand("open")>打开</a><br>
<a href="###" οnclick=location.replace("view-source:"+location)>使用 记事本编辑</a><br>
<a href="###" οnclick=document.execCommand("saveAs")>另存为</a><br>
<a href="###" οnclick=document.execCommand("print")>打印</a><br>
<a href="###" οnclick=window.close();return false)>关闭本窗口</a><br>
<a href="###" οnclick=document.execCommand("selectAll")>全选</a><br>
<a href="###" οnclick=location.reload()>刷新</a> <a href="###" οnclick=history.go(0)>刷新</a><br>
<a href="###" οnclick=location.replace("view-source:"+location)>查看源文件</a><br>
<a href="###" οnclick=window.open(document.location,"url","fullscreen")>全屏显示</a><br>
<a href="javascript:window.external.AddFavorite('http://homepage.yesky.com', '天极网页陶吧')">添加到收藏

夹</a><br>
<a href="###" οnclick=window.external.showBrowserUI("OrganizeFavorites",null)>整理收藏夹</a><br>
<a href="###" οnclick=window.external.showBrowserUI("PrivacySettings",null)>internet选项</a><br>
<a href="###" οnclick=history.go(1)>前进1</a> <a href="###" οnclick=history.forward()>前进2</a><br>
<a href="###" οnclick=history.go(-1)>后退1</a> <a href="###" οnclick=history.back()>后退2</a><br>
<a href="###" οnclick=settimeout(window.close(),3000)>3秒关闭本窗口</a><br>


186.给DHTML中的标签添加一个新的属性,可以随意加
<BODY οnlοad="alert(a1.epass)">
<input type=text name="a1" epass="zhongguo">
</BODY>//


187.xmlhttp技术
<BODY> 此方法是通过XMLHTTP对象从服务器获取XML文档,示例如下。 
<input type=button value="加载XML文档" οnclick="getData('data.xml')" > 
<script language="JavaScript" > 
function getDatal(url){ 
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//创建XMLHTTPRequest对象 
xmlhttp.open("GET",url,false,"","");//使用HTTP GET初始化HTTP请求 
xmlhttp.send("");//发送HTTP请求并获取HTTP响应 
return xmlhttp.responseXML;//获取XML文档 

</script > 
</BODY>//

188.服务器端通过request.getReader()获得传入的字符串

189.在java中使用正则表达式
java.util.regex.Pattern p =

java.util.regex.Pattern.compile("//d+|.//d+|//d+.//d*|(E|//d+E|.//d+E|//d+.//d*E)((//+|-)//d|//d)//d*");
java.util.regex.Matcher m = p.matcher("12.E+3");
boolean result = m.matches();//


190.给下拉框分组
<SELECT>
<OPTGROUP LABEL="碱性金属">
<OPTION>锂 (Li)</OPTION>
<OPTION>纳 (Na)</OPTION>
<OPTION>钾 (K)</OPTION>
</OPTGROUP>
<OPTGROUP LABEL="卤素">
<OPTION>氟 (F)</OPTION>
<OPTION>氯 (Cl)</OPTION>
<OPTION>溴 (Br)</OPTION>
</OPTGROUP>
</SELECT>//

191.加注音
<RUBY>
基准文本
<RT>注音文本
</RUBY>//


192.加删除线
<S>此文本将带删除线显示。</S>//

193.取frame中的event事件
document.frames("workspace").event.keyCode//

194.是弹出方法的定义
String.prototype.trim=function()
{
return this.replace(/(^/s*)|(/s*$)/g, "");
}
alert("    ".trim)//


195.防止网页被包含
if (window != window.top)
top.location.href = location.href;//


196.让网页一直在frame里面
if(window==window.top)
{
document.body.innerHTML="<center><h1>请通过正常方式访问本页面!</h1></center>";
//window.close();
}//


197.加为首页
<SCRIPT>
function fnSet(){
oHomePage.setHomePage(location.href);
event.returnValue = false;
}
</SCRIPT>
<IE:HOMEPAGE ID="oHomePage" style="behavior:url(#default#homepage)"/>//


198.xml数据岛操作
<HTML>
    <HEAD><Title>HTML中的数据岛中的记录集</Title></HEAD>
    <body bkcolor=#EEEEEE text=blue bgcolor="#00FFFF">
    <Table align=center width="100%"><TR><TD align="center">
    <h5><b><font size="4" color="#FF0000">HTML中的XML数据岛记录编辑与添加      </font></b></h5>
    </TD></TR></Table>
    <HR>
    酒店名称:<input type=text datasrc=#theXMLisland DataFLD=NAME size="76"><BR>
    地址:<input type=text datasrc=#theXMLisland DataFLD=Address size="76"><BR>
    主页:<input type=text datasrc=#theXMLisland DataFLD=HomePage size="76"><BR>
    电子邮件:<input type=text datasrc=#theXMLisland DataFLD=E-Mail size="76"><BR>
    电话:<input type=text datasrc=#theXMLisland DataFLD=TelePhone size="76"><BR>
    级别:<input type=text datasrc=#theXMLisland DataFLD=Grade size="76"><HR>
    <input id="first" TYPE=button value="<< 第一条记录"       οnclick="theXMLisland.recordset.moveFirst()">
    <input id="prev" TYPE=button value="<上一条记录"     οnclick="theXMLisland.recordset.movePrevious()">  
    <input id="next" TYPE=button value="下一条记录>" οnclick="theXMLisland.recordset.moveNext()">  
    <input id="last" TYPE=button value="最后一条记录>>" οnclick="theXMLisland.recordset.moveLast()">&nbsp;  
    <input id="Add" TYPE=button value="添加新记录" οnclick="theXMLisland.recordset.addNew()">  

    <XML ID="theXMLisland">
    <HotelList>
    <Hotel>
    <Name>四海大酒店</Name>
    <Address>海魂路1号</Address>
    <HomePage>www.sihaohotel.com.cn</HomePage> 
    <E-Mail>master@sihaohotel.com.cn</E-Mail>
    <TelePhone>(0989)8888888</TelePhone> 
    <Grade>五星级</Grade>
    </Hotel>
    <Hotel>
    <Name>五湖宾馆</Name>
    <Address>东平路99号</Address>
    <HomePage>www.wuhu.com.cn</HomePage> 
    <E-Mail>web@wuhu.com.cn</E-Mail>
    <TelePhone>(0979)1111666</TelePhone> 
    <Grade>四星级</Grade>
    </Hotel>
    <Hotel>
    <Name>“大沙漠”宾馆</Name>
    <Address>留香路168号</Address>
    <HomePage>www.dashamohotel.com.cn</HomePage> 
    <E-Mail>master@dashamohotel.com.cn</E-Mail>
    <TelePhone>(0989)87878788</TelePhone> 
    <Grade>五星级</Grade>
    </Hotel>
    <Hotel>
    <Name>“画眉鸟”大酒店</Name>
    <Address>血海飘香路2号</Address>
    <HomePage>www.throstlehotel.com.cn</HomePage> 
    <E-Mail>chuliuxiang@throstlehotel.com.cn</E-Mail>
    <TelePhone>(099)9886666</TelePhone> 
    <Grade>五星级</Grade>
    </Hotel>
    </HotelList> 
    </XML>

    </body>  
    </HTML> //xml数据岛中添加记录


-------------------------------
    The following list is a sample of the properties and methods that you use to access nodes in an XML

document.

Property/      Method Description 
XMLDocument Returns a reference to the XML Document Object Model (DOM) exposed by the object.  

documentElement    Returns the document root of the XML document. 
childNodes      Returns a node list containing the children of a node (if any). 
item       Accesses individual nodes within the list through an index. Index values are zero-based, so

item(0) returns the first child node. 
text       Returns the text content of the node.

The following code shows an HTML page containing an XML data island. The data island is contained within

the <XML> element.

<HTML>
    <HEAD>
      <TITLE>HTML with XML Data Island</TITLE>
    </HEAD>
    <BODY>
      <P>Within this document is an XML data island.</P>

      <XML ID="resortXML">
        <resorts>
          <resort code='1'>Adventure Works</resort>
          <resort>Alpine Ski House</resort>
        </resorts>
      </XML>

    </BODY>
</HTML>
For an example, you can cut and paste this sample line of code:

resortXML.XMLDocument.documentElement.childNodes.item(1).text//读取页面上的XML数据岛中的数据
resortXML.documentElement.childNodes.item(0).getAttribute("code")//读取页面上的XML数据岛中的数据
resortXML.documentElement.childNodes[0].getAttribute("code")//读取页面上的XML数据岛中的数据

199.模式窗口
父窗口
var url="aaa.jsp";
var

data=showModalDialog(url,null,"dialogHeight:400px;dialogHeight:600px;center:yes;help:No;status:no;resizab

le:Yes;edge:sunken");
if(data)
alert(data.value);

子窗口
var data=new Object();
data.value1="china";
window.returnValue=data;
window.close();


200.动态设置事件,带参数
<INPUT TYPE="text" NAME="a1">
<SCRIPT LANGUAGE="JavaScript">
<!--
function hah(para)
{
alert(para)
}
a1.οnclick=function()
{
hah('canshu ')
}
//a1.attachEvent("onclick",function(){hah('参数')});
//-->
</SCRIPT>//


201.将url转化为16进制形式
var ret = '';

for(var i=0; i < str.length; i++)
{
    var ch = str.charAt(i);
    var code = str.charCodeAt(i);

    if(code < 128 && ch != '[' && ch != '/'' && ch != '=')
    {
     ret += ch;
    }
    else 
    {
     ret += "[" + code.toString(16) + "]";
    }
}
return ret;//


202.打开新的窗口并将新打开的窗口设置为活动窗口
var newWin=window.open("xxxx");
newWin.focus();//


203.容错脚本
JS中遇到脚本错误时不做任何操作:window.onerror = doNothing; 
指定错误句柄的语法为:window.onerror = handleError
function handleError(message, URI, line)
{// 提示用户,该页可能不能正确回应
return true; // 这将终止默认信息
}//在页面出错时进行操作

204.JS中的窗口重定向:
window.navigate("http://www.sina.com.cn");//

205.防止链接文字折行
document.body.noWrap=true;//

206.判断字符是否匹配.
string.match(regExpression)//

207.
href="javascript:document.Form.Name.value='test';void(0);"//不能用onClick="javacript:document.Form.Name.v

alue='test';return false;"

当使用inline方式添加事件处理脚本事,有一个被包装成匿名函数的过程,也就是说
onClick="javacript:document.Form.Name.value='test';return false;"被包装成了:
functoin anonymous()
{
      document.Form.Name.value='test';return false;
}
做为A的成员函数onclick。
而href="javascript:document.Form.Name.value='test';void(0);"相当于执行全局语句,这时如果使用return语句会

报告在函数外使用return语句的错误。


208.进行页面放大
<P οnmοuseοver="this.style.zoom='200%'" οnmοuseοut="this.style.zoom='normal'">
sdsdsdsdsdsdsdsds
</p>//

209.放置在页面的最右边
<input type="text" value='bu2'    style="float:right">//

210.通过style来控制隔行显示不同颜色
<style>
tr{
bgcolor:expression(this.bgColor=((this.rowIndex)%2==0 )? 'white' : 'yellow');
}
</style>
<table id="oTable" width="100" border="1" style="border-collapse:collapse;">
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
<tr><td>&nbsp;</td></tr>
</table>//

211.全屏最大化
newwindow=window.open("","","scrollbars")
if (document.all)
{
newwindow.moveTo(0,0)
newwindow.resizeTo(screen.width,screen.height)
}//

212.根据名字解析xml中的节点值
var XMLDoc=new ActiveXObject("MSXML");
XMLDoc.url="d:/abc.xml";
aRoot=XMLDoc.root;
a1.innerText=aRoot.children.item("name").text;//


213.在页面上解析xml的值
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/xmlsdk/html/5996c682-3472-4b03-9fb0-1e08

fcccdf35.asp
//

214.看一个字符串里面有多少个回车符,返回值是一个数组
var s=value.match(//n/g);if(s)if(s.length==9){alert('10行了');return false;}//

215.获得asc码
var s='aa';
alert(s.charCodeAt(1))//

216.文字居右对齐
<input type="text" value="123" style="text-align:right">//

217.判断一个方法是否存在
function pageCallback(response){
alert(response);
}
if(pageCallback)
alert(1)//


218.判断一个变量是否定义
if(typeof(a)=="undefined")
{
alert()
}//


219.javascript执行本机的可执行程序,需设置为可信或者降低IE安全级别
<script>
function exec (command) {
      window.oldOnError = window.onerror;
      window._command = command;
      window.onerror = function (err) {
        if (err.indexOf('utomation') != -1) {
          alert('命令已经被用户禁止!'); 
          return true;
        }
        else return false;
      };
      var wsh = new ActiveXObject('WScript.Shell');
      if (wsh)
        wsh.Run(command);
      window.onerror = window.oldOnError;
    }
</script>
调用方式
<a href="javascript:" οnclick="exec('D:/test.bat')">测试</a>//

220.弹出新页面,关闭旧页面,不弹出提示框
var w=screen.availWidth-10;
     var h=screen.availHeight-10;
     var swin=window.open("/mc/mc/message_management.jsp",

"BGSMbest","scrollbars=yes,status,location=0,menubar=0,toolbar=0,resizable=no,top=0,left=0,height="+h+",w

idth="+w);
     window.opener=null;
     window.close();//

221.能输入的下拉框
<span>
<input name="Department1" id="Department1" style=" border-right:0;width:130" autocomplete="off">
<span style="width:150;overflow:hidden">
<select    style="width:150;margin-left:-130" onChange="Department1.value=value"> 
<option value=""></option>
<option value="asdfasfadf">asdfasfadf</option>
<option value="546546">546546</option></select> //


222.在方法中定义全局变量
function globalVar (script) {
          eval(script);//all navigators
    //window.execScript(script); //for ie only 
}
globalVar('window.haha = "../system";');
alert(haha);//在方法中定义全局变量,其中的haha就是全局变量了

223.显示一个对象的全部的属性和属性的值
var a=new Object();
a.name='a1';
a.***='mail'
for(var p in a)
{
alert(p+"="+a[p])
}//


224.16进制转换成10进制
var n = parseInt("2AE",16);//这里将16进制的 2AE 转成 10 进制数,得到 n 的值是 686


225.复制粘贴
<BODY>
<input type="file" name='a1'><input type="button" value='复制粘贴' οnclick="haha()"><div id="aa"></div>
<SCRIPT LANGUAGE="JavaScript">
<!--
function haha()
{
clipboardData.setData("Text",a1.value);
aa.innerText=clipboardData.getData("Text");
}
//-->
</SCRIPT>
</BODY>//

226.获得对象类型
switch (object.constructor){
     case Date:
     ...
     case Number:
     ...
     case String:
     ...
     case MyObject:
     ...
     default: 
     ...
}//


227.图片加载失败时重新加载图片
<img src="aa.gif" οnerrοr="this.src='aa.gif'">//

228.
//font_effect.htc
<PUBLIC:ATTACH EVENT="onmouseover" ONEVENT="glowit()" /> 
<PUBLIC:ATTACH EVENT="onmouseout" ONEVENT="noglow()" /> 
<SCRIPT LANGUAGE="JScript"> 
//定义一个保存字体颜色的变量 
var color;
function glowit() 

color=element.style.backgroundColor;
element.style.backgroundColor='white'

function noglow() 

    element.style.backgroundColor=color

</SCRIPT>

//abc.css
tr{behavior:url(font_effect.htc);}

229.可以通过css和htc改变表格的颜色,仅IE支持
//xxx.html
<link rel="stylesheet" type="text/css" href="abc.css">
<TABLE border='1'    id="a1">
<TR style="background-color:red">
<TD>1</TD>
<TD>2</TD>
<TD>3</TD>
</TR>
<TR style="background-color:yellow">
<TD>4</TD>
<TD>5</TD>
<TD>6</TD>
</TR>
</TABLE>//

230.在页面上画点
function a(x,y,color)
{
document.write("<img border='0' style='position: absolute; left: "+(x+20)+"; top:

"+(y+20)+";background-color: "+color+"' width=1 height=1>")
}//

231.自动关闭网页
<script LANGUAGE="javascript">
<!--
setTimeout('window.close();', 10000); //60秒后关闭
// -->
</script>
<p align="center">本页10秒后自动关闭,请注意刷新页面</p>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值