JAVA

人生若只如初见,何事秋风悲画扇。

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  50 随笔 :: 25 文章 :: 157 评论 :: 0 Trackbacks
以下是本人在代码中常用到的一些JS脚本,虽然是一些简单而又短小的function却是帮了我不少的忙呢!希望对大家有些用,有了好的再贴上来 ^_^
1:在一带到复杂的FRAME页面中OPEN一个窗体来(当然不用什么parent.parent啦)
function  checkuser(name)
    
{
        window.open(
" about:blank " , " zhutong " , 'menubar = 0 ,width = 350 ,height = 240 ,left = 230 ,top = 200 ,resizable = 0 ,scrollbars = auto');
        window.document.forms['form1'].target 
=   " zhutong " ;
        window.document.forms['form1'].action 
=   " Account/check.jsp?username= " + name;
        window.document.forms['form1'].submit();        
    }

以下的LINK来触发
<href="javascript:checkuser(window.document.forms['SignUpForm'].name.value);">
                                        
<bean:message key="account.signup.input.name.check" />
                                    
</a>

当然下面的不能少啦!
</html:form>
<form name="form1" method="post" action="">
</form>

2:关闭一当前窗口,并且无关闭提示(这个功能太常用了)
<input type="submit" name="Submit" value="知道啦" onClick='window.opener = "xxx";
    window.close();'
>


3:让一个链接自动提交:
如有一个链接:

<href="xx.htm" name="multiuse">AAA</a>


则可以:

var urlfir = studyezurl + '/Authentication.do?actionid=ForgetPassword';
var urlsec = studyezurl + '/tempURL.do';
multiuse.href 
= urlsec;
multiuse.focus();
multiuse.click();
multiuse.href 
= urlfir;  //这个好象不起作用,所以最好将此urlfir设成在href中的默认值


在STRUTS中有一个多个FRAME构成的系统.点击注销后想固定到某一页面!(这个鬼费了我不少时间 ^_^ )


4:让HTML也有JSP中的request.getParameter("");
HTML也可以通过JS来到得参数,函数如下(我将它保存到了一个数组里面):

//--------------------------------------------------------------------------
//
Name: GetArgsFromHref
//
//
Pupers: the function will get the parameters from the server
//
//
Parameter:
//
sHref---->>the current URL
//
sArgName---->>the Array store the name of parameters which you want to get
//
//
Return: Array to store the result
//
//
Author: Jkallen
//
----------------------------------------------------------------------------
function GetArgsFromHref(sHref, sArgName)
{
    
var args  = sHref.split("?");
    
var p_Result = new Array();
    
    
if(args[0== sHref) 
    
{
         
return p_Result; 
    }
  
    
var str = args[1];
    args 
= str.split("&");
    
for(var i = 0; i < args.length; i ++)
    
{
        str 
= args[i];
        
var arg = str.split("=");
        
if(arg.length <= 1
            
continue;
        
if(sArgName != null)
        
{
            
for(var c1 = 0; c1 < sArgName.length; c1++)
            
{
                
var tempValue = arg[0];
                
if( tempValue == sArgName[c1])
                    p_Result[tempValue] 
= arg[1];
            }
   
        }
//end if
     }
//end for
     
     
return p_Result;
 }
//end GetArgsFromHref


所以你以后就可以通过如:

var curCourseID = pValue[c_courseID];


的样子来直接取了啦,c_courseID是参数名称哦

5:在页面动态显示当前时间

<span id="aa">当前时间</span><script>setInterval("aa.innerHTML=new Date().toLocaleString()+' 星期'+'日一二三四五六'.charAt(new Date().getDay());",1000);
</script> 

1000就表示了,每隔1000毫秒就更新一次aa里面的内容.

6:对WEB页面对象的常用操作,
.select()  选中对象(文本框)的内容
.focus()   让某个对象获取焦点
checked  检查单选按钮是否处于选中状态
若存的是一组单选按钮,根据document的一些方法:

getElementById     获取对 ID 标签属性为指定值的第一个对象的引用。
getElementsByName     根据 NAME 标签属性的值获取对象的集合。
getElementsByTagName     获取基于指定元素名称的对象集合。
可以用getElementsByName来解决,它是取得一些同名对象的集合,与getElementById(指定值的第一个对象的引用)不同.如下所示:

var tmppara = document.getElementsByName("para"+i);
   
var j=0;
   
for(;j<tmppara.length;j++){
    
if(tmppara[j].checked){
      values[cur_index] 
= tmppara[j].value;
      cur_index
++;
     }

   }

7:确定下拉框的值:

<script language="javascript">
function test(){
 
var se = document.form1.select;
 
for(i=0;i<se.length;i++){
  
if(se.options[i].value == 55){
   se.options[i].selected
=true;
   
break;
  }
    
 }

 
}

</script>

HTML 如下:

<form id="form1" name="form1" method="post" action="">
    
<select name="select">
    
<option value="11" selected="">11</option>
    
<option value="22">22</option>
    
<option value="33">33</option>
    
<option value="44">44</option>
    
<option value="55">55</option>
  
</select>
</form>

删除其中的一个option:
se.options.remove(1);
其中参数1表示下标

8:使得某一对象不可用(可用刚改成false)
document.form1.submit2.disabled=true;
使得某一对象不可见(可见则改成visible)
document.form1.submit2.style.visibility="hidden";

9:日期以'yyyy-mm-dd'(2006-09-07 or 2006-9-17)

function chkdate(value)
{
    
var datestr;
    datestr
=value;
    
var lthdatestr;
    
if (datestr != "")
        
{lthdatestr= datestr.length} ;
    
else
        
{lthdatestr=0};    
    
var tmpy="";
    
var tmpm="";
    
var tmpd="";
    
var status;
    status
=0;
    
if ( lthdatestr== 0)
        
{return (false)};            
    
for (i=0;i<lthdatestr;i++)
    
{    if (datestr.charAt(i)== '-')
        
{
            status
++;
        }

        
if (status>2)
        
{
            
return (false);
        }

        
if ((status==0&& (datestr.charAt(i)!='-'))
        
{
            tmpy
=tmpy+datestr.charAt(i);
        }

        
if ((status==1&& (datestr.charAt(i)!='-'))
        
{
            tmpm
=tmpm+datestr.charAt(i);
        }

        
if ((status==2&& (datestr.charAt(i)!='-'))
        
{
            tmpd
=tmpd+datestr.charAt(i);
        }


    }

    year
=new String (tmpy);
    month
=new String (tmpm);
    day
=new String (tmpd);
    
if ((tmpy.length!=4|| (tmpm.length>2 || tmpm.length<1|| (tmpd.length!=2))
    
{
        
return (false);
    }

    
if (!((1<=month) && (12>=month) && (31>=day) && (1<=day)) )
    
{
        
return (false);
    }

    
if (!((year % 4)==0&& (month==2&& (day==29))
    
{
        
return (false);
    }

    
if ((month<=7&& ((month % 2)==0&& (day>=31))
    
{
        
return (false);
    
    }

    
if ((month>=8&& ((month % 2)==1&& (day>=31))
    
{
        
return (false);
    }

    
if ((month==2&& (day==30))
    
{
        
return (false);
    }

    
return (true);
}

再加一个比较函数,刚刚写的

/************************************************************
 *将yyyy-mm-dd的日期型数据换成数字型以比较大小 add by zhangyinxin
************************************************************
*****/

function changDate2Num(date){
    
var tmp = date.split('-') ;
    
var result;
    
if(tmp.length<=0){
        alert('日期格式(yyyy
-mm-dd)不正确!');
    }
else{
        result 
= tmp[0];
        
if(tmp[1].length<2)    tmp[1= "0"+tmp[1];
        result 
+= tmp[1]; 
        
if(tmp[2].length<2)    tmp[2= "0"+tmp[2];
        result 
+= tmp[2]; 
    }

//    alert(result);
    return tmp;
}

10:对一组单选按钮的处理---是否选中or返回选中值

function getValueofCheckBoxSelected_this(dyfs)
{
    
var controlarray = document.getElementsByName(dyfs);
    
if(controlarray==null||controlarray.length==0)
        
return false;
       
for (var i=0; i<controlarray.length; i++)
       
{
        
if(controlarray[i].checked)
            
return controlarray[i].value;    
            
//如果要返回是否选中,这儿返回true啦,下面返回false    
    }
    
    
return null;
}

11,从A页面打开一个页面B,从B中输入相关信息后再从B页面把信息传到A页面处理:
从A页面打开B页面的方法:

function addPersonInfo(){
  
var obj =
  window;
  
var url = "<%=contextpath%>/jsp/addinfo.jsp"
;
  window.showModalDialog(url,obj,'dialogwidth
=500px; dialogheight=300px;status=no; help=
no');
}

主要是其中的obj参数起作用.然后在B页面 中返回:

.
var obj =
 window.dialogArguments;
    obj.addRow(username,phone,email);
    window.close();

注意这儿只取了主要部分:username,phone,emial均是在B页面取得一些信息obj.addRow()中addRow是A页面中定义的,如下:

/******************************************************************
@name addRow---为******增加一行
@parameters    null
@retrun null
@author zhangyinxin
*****************************************************************
*/

function addRow(name,phone,email){
    do something......
}


12:得用JS在WEB页面中动态增加行列:
这里主要用到了innerHTML, cells,rows,appendChild等一些方法与属性有了它们基本上就OK了,更多可以参考HTML的参考手册,可以做到如在DW更改界面一样,感觉很爽(比如更改对象的title ,id ,style, name)!

dateTr = document.getElementById("tr_name");//它实际上是一列也就是<tr></tr>'tr_name'是我自定义
    NewTr = document.all.dyzmx.cloneNode(true);
    NewTr.style.display 
= "block";
    
var cur_lxr_xm = dateTr.parentNode.rows[1].cells[1].innerHTML;
    dateTr.parentNode.appendChild(NewTr.cloneNode(
true));
    
var added_new_tr = dateTr.parentNode.lastChild;    
..

主要用到了cloneNode方法,其它更多可以参考关于HTML的对象介绍,然后再通过appendChild来增加一行(在此是增加一行).当然也可以自己定义一些元素来初始化innerHTML,as :

html = " <INPUT type=text style=\"width:30px;\" value="+k+" name=\"rwbh\" maxlength=3>";
        start.getElementsByTagName(
"tr")[k].firstChild.innerHTML = html;

顺便说一下关于删除:

var child_len = dateTr.parentNode.rows.length-1;
        
for(c2=child_len; c2>0; c2--){
            
var rows = [];
            
if(name=='lxr')
                
if(dateTr.parentNode.rows[c2].title=='lxr_data'){
                    rows.push(dateTr.parentNode.rows[c2]);
                    
for(var i=0;i<rows.length;i++){
                        rows[i].parentNode.removeChild(rows[i]);
                    }

}        
                }

注意这种方法删除时,一不小心不犯错了.一方面for(c2=child_len; c2>0; c2--)应该是递减的方式来遍历(因为rows里面push的时候,与删除的时候节点是反向的,当然假如取rows的时候反向取也OK的),另一方面 dateTr.parentNode.rows.length-1不可以直接放到for里面(因为 dateTr.parentNode.rows.length-1的长值每在for里面跑一次就变一次,当然是变小啦).

所以也可以如下处理:

/******************************************************************
@name delRow---为******删除选项中行
@parameters    null
@retrun null
@author zhangyinxin
*****************************************************************
*/

function delRow(){
    
var checkboxs = document.getElementsByName("checkspecial");
    
var rows = [];
    
for(var i=0;i<checkboxs.length;i++){
        
if(checkboxs[i].checked && checkboxs[i].parentNode.parentNode.title!='tmp'){
            rows.push(checkboxs[i].parentNode.parentNode);
        }

    }

    
for(var i=0;i<rows.length;i++){
        rows[i].parentNode.removeChild(rows[i]);
    }

}

我这儿用到了复选框,当然这并不影响删除的效果实现,它不过是一种删除条件罢了(比如title也是哦)

13:第一次见到这样的自定义函数:

function $() {
  
var elements = new
 Array();

  
for (var i = 0; i < arguments.length; i++
{
    
var element =
 arguments[i];
    
if (typeof element ==
 'string')
      element 
=
 document.getElementById(element);

    
if (arguments.length == 1
)
      
return
 element;

    elements.push(element);
  }


  
return elements;
}



应用如下:

this.removeRow  =  function(_id){  
                       
var  row  =  $(this.id  +  "_row_"+
_id);  
                       
if(!row)return
;  
                       row.parentNode.removeChild(row);  
           }
 

感觉蛮不错!(原来这些是protype.js中的东东呢,呵呵 这二天看了下prototype.js原来它是为ruby写的框架,不过这个东东确实不错哦!)

14:javascript验证表单时常用

"^-[0-9]*[1-9][0-9]*$"  //负整数

"^-?\d+$"    //整数

"^\d+(\.\d+)?$"  //非负浮点数(正浮点数 + 0)

"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$"  //正浮点数

"^((-\d+(\.\d+)?)|(0+(\.0+)?))$"  //非正浮点数(负浮点数 + 0)

"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  //负浮点数

"^(-?\d+)(\.\d+)?$"  //浮点数

"^[A-Za-z]+$"  //由26个英文字母组成的字符串

"^[A-Z]+$"  //由26个英文字母的大写组成的字符串

"^[a-z]+$"  //由26个英文字母的小写组成的字符串

"^[A-Za-z0-9]+$"  //由数字和26个英文字母组成的字符串

"^\w+$"  //由数字、26个英文字母或者下划线组成的字符串

"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"    //email地址

"^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$"  //url


呵呵 我一天添一些JS上来,可惜朋友们看不到,因为这"贴子"沉下去了.没办法,可是它们真的帮我不少忙,我自己的也常到这儿来取经....

以后不用序号了,直接改用日期
06.7.18:今天我用JS产生一个checkbox,别的都没事,就是在设置默认让它选中时花了些时间:
以下是代码:
input = document.createElement("input");
   input.setAttribute("type","checkbox");
   //input.defaultChecked = true;---此语句可以直接在产生checkbox的时候让它默认选中
   input.setAttribute("value","1");
   $('kdydx').appendChild(input);
   $('kdydx').lastChild.setAttribute("checked","ckecked");//要想通过setAttribute来设置,刚必须在appendChild之后
关于它的答案我在
http://forum.java.sun.com/thread.jspa?threadID=628633&messageID=3606303找到的。

//打印
function send_dy(){
 var bdhtml=window.document.body.innerHTML;
 sprnstr="<!--startprint-->";
 eprnstr="<!--endprint-->";
 prnhtml=bdhtml.substring(bdhtml.indexOf(sprnstr)+17);
 prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
 window.document.body.innerHTML=prnhtml;
 window.print();
 window.document.body.innerHTML=bdhtml;
}

/**
 调用IE的打印控件打印TABLE
 tb为要打印的TABLE的ID
 pSzize为一页的行数
**/

function tablePrint(tb,pSize,title){
 var nw = window.open('','','top=50,left=100,resizable=yes,width=800,height=600,titlebar=yes,menubar=no,status=no,location=no,scrollbars=yes');
 nw.document.open("text/html","GB2312")
 nw.document.write("<style media=print>");
 nw.document.write(".Noprint{display:none;}");//不需要打印的样式
 nw.document.write(".PageNext{page-break-after: always;}");//
 nw.document.write(".data_Table{border-color:#000000;border-width:1px;border-style:solid;}");
 nw.document.write("</style>");
 nw.document.write("<style>");
 nw.document.write(".Mb_Input_Button{height:20px;border-left:1px solid #DAE8F7; border-top:1px solid #DAE8F7; border-right:1px solid #A0C4EB;border-bottom:1px solid #A0C4EB;background-color:#E4EBF3;padding-left:5px;padding-right:5px;margin:4px 5px 2px 0px;}");
 nw.document.write(".noShow{display:none;}");//打印预览时不需要显示的样式
 nw.document.write("</style>");
 nw.document.write("<HEAD><TITLE>&nbsp;</TITLE></HEAD>");
 nw.document.write("<body>");
 nw.document.write("<div align='right'>");
 nw.document.write("<input type=button value='打印' onclick='document.all.WebBrowser.ExecWB(6,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
  nw.document.write("<input type=button value='页面设置' onclick='document.all.WebBrowser.ExecWB(8,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
  nw.document.write("<input type=button value='打印预览' onclick='document.all.WebBrowser.ExecWB(7,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
 nw.document.write("</div>");
 nw.document.write("<OBJECT  id=WebBrowser  classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2  height=0  width=0 VIEWASTEXT></OBJECT>");
 nw.document.write("<div align='center' style='margin-top:5; margin-bottom:5'><b>"+title+"</b></div>");
 var obj=document.getElementById(tb);
 var trObj=obj.childNodes[0].childNodes;
 for(i=0;i<trObj.length;i++){
   if((i!=0)&&(i%pSize==0)){
   trObj[i].className="PageNext";
   }
  }
 nw.document.write(document.getElementById(tb).outerHTML);
 nw.document.write("</body>");
}

/**
 调用IE的打印控件打印对象
 tb为要打印的TABLE的ID
 pSzize为一页的行数
**/
function objPrint(tb,title){
 var nw = window.open('','','top=50,left=100,resizable=yes,width=800,height=600,titlebar=yes,menubar=no,status=no,location=no,scrollbars=yes');
 nw.document.open("text/html","GB2312")
 nw.document.write("<style media=print>");
 nw.document.write(".Noprint{display:none;}");//不需要打印的样式
 nw.document.write(".PageNext{page-break-after: always;}");//
 nw.document.write(".data_Table{border-color:#000000;border-width:1px;border-style:solid;}");
 nw.document.write("</style>");
 nw.document.write("<style>");
 nw.document.write(".Mb_Input_Button{height:20px;border-left:1px solid #DAE8F7; border-top:1px solid #DAE8F7; border-right:1px solid #A0C4EB;border-bottom:1px solid #A0C4EB;background-color:#E4EBF3;padding-left:5px;padding-right:5px;margin:4px 5px 2px 0px;}");
 nw.document.write(".noShow{display:none;}");//打印预览时不需要显示的样式
 nw.document.write("</style>");
 nw.document.write("<HEAD><TITLE>&nbsp;</TITLE></HEAD>");
 nw.document.write("<body>");
 nw.document.write("<div align='right'>");
 nw.document.write("<input type=button value='打印' onclick='document.all.WebBrowser.ExecWB(6,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
  nw.document.write("<input type=button value='页面设置' onclick='document.all.WebBrowser.ExecWB(8,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
  nw.document.write("<input type=button value='打印预览' onclick='document.all.WebBrowser.ExecWB(7,1);' class='NOPRINT Mb_Input_Button'>&nbsp;");
  nw.document.write("<input type=button value='关闭' onclick='document.all.window.close();' class='NOPRINT'>");
 nw.document.write("</div>");
 nw.document.write("<OBJECT  id=WebBrowser  classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2  height=0  width=0 VIEWASTEXT></OBJECT>");
 nw.document.write("<div align='center' style='margin-top:5; margin-bottom:5'><b>"+title+"</b></div>");
 nw.document.write(document.getElementById(tb).outerHTML);
 nw.document.write("</body>");
}

/**
 中文英文混合时字符串的长度计算
 一个汉字2个字节
**/
String.prototype.length2 = function() {
    var cArr = this.match(/[^x00-xff]/ig);
    return this.length + (cArr == null ? 0 : cArr.length);
}
...   ....

posted on 2006-03-06 17:05 Jkallen 阅读(3109) 评论(3)  编辑  收藏 所属分类: AJAX

评论

# re: 妙用javascript 2006-03-06 21:27 剑事
function checkuser(name)
{
window.open("about:blank","zhutong", 'menubar=0,width=350,height=240,left=230,top=200,resizable=0,scrollbars=auto');
window.document.forms['form1'].target = "zhutong";
window.document.forms['form1'].action = "Account/check.jsp?username="+name;
window.document.forms['form1'].submit();
}
可以改成这样
function checkuser(name)
{
window.open("Account/check.jsp?username="+name,"zhutong", 'menubar=0,width=350,height=240,left=230,top=200,resizable=0,scrollbars=auto');

}


<a href="javascript:checkuser(window.document.forms['SignUpForm'].name.value);">
<bean:message key="account.signup.input.name.check" />
</a>
这个可以改成这样
<a href="javascript:checkuser(SignUpForm.name.value);">
<bean:message key="account.signup.input.name.check" />
</a>
  回复  更多评论
  

# re: 妙用javascript 2006-03-07 08:48 Jkallen
谢谢
有道理!  回复  更多评论
  

# re: 妙用javascript 2006-06-29 10:53 nina
很好 收藏  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: