Javascript:Javascript教程,javascript入门,学习笔记

来源:互联网 发布:关系数据库逻辑模型 编辑:程序博客网 时间:2024/05/23 13:07

Javascript教程,javascript入门,学习笔记

1.基本控件的使用

控件名.value

控件名.value

控件名[i].checked    .value 

for each ob in控件名
   if ob.checked then
      window.alert ob.value
next

控件名.checked    .value


 
  
单行         多行         多选

添加选项

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自动换行
 
使用TextAreaWrap属性

 

  • 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">
9.可以在收藏夹中显示出你的图标

 <link rel="Bookmark" href="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.获得本页urlrequest.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)应用:计算字符串的长度(一个双字节字符长度计2ASCII字符计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" 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个字符串合起来是不是日期或者判断该天是不是存在。这里month0开始,故和实际值差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.如何在另一个窗体对原来窗体进行操作
 
在打开的新窗体,用window.opener来访问原来窗体的对象。例如  alert(window.opener.hiddens.value);
 
可以对层进行重写Html代码,例如
window.opener.divStatus.innerHTML="Proctored";
43.层的隐藏与显示
  
只要设置层的styledisplay属性即可。 比如<div style="display:none" id="divTest">隐藏的层</div>
  
如果要显示它可以通过脚本来控制。例如divTest.style.display = "";  或者
  window.document.getElementById("MyDiv").style.display = "";
44.禁止右键
<body oncontextmenu="return false">
45.得到当前显示器的分辨率
window.srceen.width
得到屏幕的宽度
window.srceen.height
得到屏幕的高度
46.定时运行特定代码
setTimeout(Code,Timeout);  
是从现在算起多少微秒后运行该代码(只运行一次)
setInterval(Code,Timeout); 
是每隔多少微秒运行一次代码
Code
是一段字符串,里边是js代码,Timeout是时间间隔,单位是微秒

<input name="txtTimer" value="10
">
<SCRIPT LANGUAGE=javascript>
<!--
    waitTime=10000; //10

    timer=setInterval("OnTimer()",1000);

    function OnTimer(){
        waitTime=waitTime-1000;
        if(waitTime==0){
            window.close();
        }
        txtTimer.value=waitTime/1000+"
";
    }
//-->
</SCRIPT>

47.得到本页网址
var Url = window.location.href;
48.保存当前页面的内容
document.execCommand("SaveAs","","C://index.htm");
49.用模式窗体,打开一个参数获取窗体
主窗体中用
   var returnvalue=window.showModalDialog('../webPri/GetDate.asp',frmApplyPriItem,"status=no; help=no; dialogWidth=320px; dialogHeight=120px;");

子窗体中用
   window.returnValue="OK";
   window.dialogArguments.FormObject.value
50.Web打印文档
<!--
语言无关 保存成 .HTML-->
<html>
<head>
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
<title>
网络打印模板页
</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<!--media=print
这个属性可以在打印时有效
-->
<style media=print>
.Noprint{display:none;}
.PageNext{page-break-after: always;}
</style>

<style>
.tdp
{
border-bottom: 1 solid #000000;
border-left: 1 solid #000000;
border-right: 0 solid #ffffff;
border-top: 0 solid #ffffff;
}
.tabp
{
border-color: #000000 #000000 #000000 #000000;
border-style: solid;
border-top-width: 2px;
border-right-width: 2px;
border-bottom-width: 1px;
border-left-width: 1px;
}
.NOPRINT {
font-family: "
宋体
";
font-size: 9pt;
}
</style>
</head>
<body >
<center class="Noprint" >
<p>
<OBJECT id=WebBrowser classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 width=0>
</OBJECT>
<input type=button value=
打印
onclick=document.all.WebBrowser.ExecWB(6,1)>
<input type=button value=
直接打印
onclick=document.all.WebBrowser.ExecWB(6,6)>
<input type=button value=
页面设置
onclick=document.all.WebBrowser.ExecWB(8,1)>
</p>
<p> <input type=button value=
打印预览
onclick=document.all.WebBrowser.ExecWB(7,1)>
<br/>
</p>
<hr align="center" width="90%" size="1" noshade>
</center>

<table width="90%" border="0" align="center" cellpadding="2" cellspacing="0" class="tabp">
<tr>
<td colspan="3" class="tdp">
1
</td>
</tr>
<tr>
<td width="29%" class="tdp">
 
</td>
<td width="28%" class="tdp">
 
</td>
<td width="43%" class="tdp">
 
</td>
</tr>
<tr>
<td colspan="3" class="tdp">
 
</td>
</tr>
<tr>
<td colspan="3" class="tdp"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50%" class="tdp"><p>
这样的报表
</p>
<p>
对一般的要求就够了。
</p></td>
<td>
 
</td>
</tr>
</table></td>
</tr>
</table>
<hr align="center" width="90%" size="1" noshade class="NOPRINT" >
<!--
分页
-->
<div class="PageNext"></div>
<table width="90%" border="0" align="center" cellpadding="2" cellspacing="0" class="tabp">
<tr>
<td class="tdp">
2
</td>
</tr>
<tr>
<td class="tdp">
看到分页了吧
</td>
</tr>
<tr>
<td class="tdp">
 
</td>
</tr>
<tr>
<td class="tdp">
 
</td>
</tr>
<tr>
<td class="tdp"><table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50%" class="tdp"><p>
这样的报表
</p>
<p>
对一般的要求就够了。
</p></td>
<td>
 
</td>
</tr>
</table></td>
</tr>
</table>
</body>
</html>

在基于框架的网页打印时,用如下函数可以打印某个框架内的网页

<input type=button onclick="printweb(this)">
<script>
function printweb()
{
   this.focus();
   window.print();
}
</script>

 浏览(47) | 评论(0) | 06-18 11:51

eclipse下的打包插件fatjar

ECLIPSE下,如果要将JAVA应用程序打包的话,一般用file菜单下的EXPORT就可以EXPORTJAR文件里,但如果工程里有其他的库文件的话,那ECLIPSE就无能为力了,这时,可以到
http://sourceforge.net/project/showfiles.php?group_id=115990&package_id=125924
下载,解压将文件夹拷贝到eclipseplugins下,重新启动Eclipse3.1,Windows=>prefernce=>fat jar preference看到他就说明已经安装成功了。
      
再在FILE菜单下,用Export..=>向导里有fat jar =>,接着就可以按着向导使用了

       Eclipse快速上手指南之使ANT
  AntJava平台下非常棒的批处理命令执行程序,能非常方便地自动完成编译,测试,打包,部署等等一系列任务,大大提高开发效率。如果你现在还没有开始使用Ant,那就要赶快开始学习使用,使自己的开发水平上一个新台阶。

  Eclipse中已经集成了Ant,我们可以直接在Eclipse中运行Ant
  以前面建立的Hello工程为例,创建以下目录结构:

       新建一个build.xml,放在工程根目录下。build.xml定义了Ant要执行的批处理命令。虽然Ant也可以使用其它文件名,但是遵循标准能更使开发更规范,同时易于与别人交流。

  通常,src存放Java源文件,classes存放编译后的class文件,lib存放编译和运行用到的所有jar文件,web存放JSPweb文件,dist存放打包后的jar文件,doc存放API文档。

  然后在根目录下创建build.xml文件,输入以下内容:

?xml version="1.0"?
project name="Hello world" default="doc"

!-- properies --
property name="src.dir" value="src" /
property name="report.dir" value="report" /
property name="classes.dir" value="classes" /
property name="lib.dir" value="lib" /
property name="dist.dir" value="dist" /
property name="doc.dir" value="doc"/

!-- 定义classpath --
path id="master-classpath"
fileset file="${lib.dir}/*.jar" /
pathelement path="${classes.dir}"/
/path

!-- 初始化任务 --
target name="init"
/target

!-- 编译 --
target name="compile" depends="init" description="compile the source files"
mkdir dir="${classes.dir}"/
javac srcdir="${src.dir}" destdir="${classes.dir}" target="1.4"
classpath refid="master-classpath"/
/javac
/target

!-- 测试 --
target name="test" depends="compile" description="run junit test"
mkdir dir="${report.dir}"/
junit printsummary="on"
haltonfailure="false"
failureproperty="tests.failed"
showoutput="true"

classpath refid="master-classpath" /
formatter type="plain"/
batchtest todir="${report.dir}"
fileset dir="${classes.dir}"
include name="**/*Test.*"/
/fileset
/batchtest
/junit
fail if="tests.failed"
***********************************************************
**** One or more tests failed! Check the output ... ****
***********************************************************
/fail
/target

!-- 打包成jar --
target name="pack" depends="test" description="make .jar file"
mkdir dir="${dist.dir}" /
jar destfile="${dist.dir}/hello.jar" basedir="${classes.dir}"
exclude name="**/*Test.*" /
exclude name="**/Test*.*" /
/jar
/target

!-- 输出api文档 --
target name="doc" depends="pack" description="create api doc"
mkdir dir="${doc.dir}" /
javadoc destdir="${doc.dir}"
author="true"
version="true"
use="true"
windowtitle="Test API"

packageset dir="${src.dir}" defaultexcludes="yes"
include name="example/**" /
/packageset
doctitle><![CDATA[h1Hello, test/h1]]></doctitle
bottom><![CDATA[iAll Rights Reserved./i]]></bottom
tag name="todo" scope="all" description="To do:" /
/javadoc
/target
/project

        以上xml依次定义了init(初始化),compile(编译),test(测试),doc(生成文档),pack(打包)任务,可以作为模板。
  选中Hello工程,然后选择“Project”“Properties”“Builders”“New…”,选择“Ant Build”

填入NameAnt_BuilderBuildfilebuild.xmlBase Directory${workspace_loc:/Hello}(按“Browse Workspace”选择工程根目录),由于用到了junit.jar包,搜索Eclipse目录,找到junit.jar,把它复制到Hello/lib目录下,并添加到AntClasspath中:

       然后在Builder面板中钩上Ant_Build,去掉Java Builder

       再次编译,即可在控制台看到Ant的输出:

Buildfile: F:/eclipse-projects/Hello/build.xml

init:

compile:
[mkdir] Created dir: F:/eclipse-projects/Hello/classes
[javac] Compiling 2 source files to F:/eclipse-projects/Hello/classes


test:
[mkdir] Created dir: F:/eclipse-projects/Hello/report
[junit] Running example.HelloTest
[junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.02 sec


pack:
[mkdir] Created dir: F:/eclipse-projects/Hello/dist
[jar] Building jar: F:/eclipse-projects/Hello/dist/hello.jar


doc:
[mkdir] Created dir: F:/eclipse-projects/Hello/doc
[javadoc] Generating Javadoc
[javadoc] Javadoc execution
[javadoc]
Loading source files for package example...
[javadoc] Constructing Javadoc information...
[javadoc] Standard Doclet version 1.4.2_04
[javadoc] Building tree for all the packages and classes...
[javadoc] Building index for all the packages and classes...
[javadoc] Building index for all classes...
[javadoc] Generating F:/eclipse-projects/Hello/doc/stylesheet.css...
[javadoc] Note: Custom tags that could override future standard tags: @todo. To avoid potential overrides, use at least one period character (.) in custom tag names.
[javadoc] Note: Custom tags that were not seen: @todo
BUILD SUCCESSFUL
Total time: 11 seconds


  Ant依次执行初始化,编译,测试,打包,生成API文档一系列任务,极大地提高了开发效率。将来开发J2EE项目时,还可加入部署等任务。并且,即使脱离了Eclipse环境,只要正确安装了Ant,配置好环境变量ANT_HOME=Ant解压目录>,Path=…;%ANT_HOME%/bin,在命令行提示符下切换到Hello目录,简单地键入ant即可。

 浏览(59) | 评论(0) | 06-14 10:18

jar打包的用法

用法:jar {ctxu}[vfm0Mi] [jar-文件] [manifest-文件] [-C 目录] 文件名 ...
选项:

   -c 
创建新的存档
   -t 
列出存档内容的列表
   -x 
展开存档中的命名的(或所有的〕文件
   -u 
更新已存在的存档
   -v 
生成详细输出到标准输出上
   -f 
指定存档文件名
   -m 
包含来自标明文件的标明信息
   -0 
只存储方式;未用ZIP压缩格式
   -M 
不产生所有项的清单(manifest〕文件
   -i 
为指定的jar文件产生索引信息
   -C 
改变到指定的目录,并且包含下列文件:
如果一个文件名是一个目录,它将被递归处理。
清单(manifest〕文件名和存档文件名都需要被指定,按'm' 'f'标志指定的相同顺

示例1:将两个class文件存档到一个名为 'classes.jar' 的存档文件中:
      jar cvf classes.jar Foo.class Bar.class
示例2:用一个存在的清单(manifest)文件 'mymanifest' foo/ 目录下的所有
         
文件存档到一个名为 'classes.jar' 的存档文件中:
      jar cvfm classes.jar mymanifest -C foo/ .
1

 

 
原创粉丝点击