常用JavaScript函数 1 - 15 (自我总结)

常用JavaScript函数 16 - 30(自我总结)

 

 

31、获得当前日期

32、 jquery 操作 radio

33、 双击滚屏

34、 框架显示/隐藏

35、 JavaScript中的var_dump

36、 为 JavaScript 添加 in_array  支持二维数组

37、 支持div的抖动

38、 JavaScript中的empty();

39、 input or area 显示/隐藏 提示信息

40、 str_replace

41、 implode / explode

42、 全选

43、 去除数组中的重复项

44、 用JavaScript动态加载CSS和JS文件

45、 用JavaScript生成菜单树(build_file_tree) 需要得到JSON

46、 textarea自动适应高度

 

31、获得当前日期

 

<script language='javascript'> 
	function startTime(){ 
		var today=new Date(); 
		var y = today.getFullYear();
		var m = today.getMonth();
		var t = today.getDate();
		var d = today.getDay();
		var h = today.getHours(); 
		var i = today.getMinutes(); 
		var s = today.getSeconds(); 

		var weekday = {
				'0': '星期日',
				'1': '星期一',
				'2': '星期二',
				'3': '星期三',
				'4': '星期四',
				'5': '星期五',
				'6': '星期六'
			};

		//add a zero in front of number<10 
		i = checkTime(i); 
		s = checkTime(s); 

		document.getElementById('txt').innerHTML = '今天是: ' + y + '年 ' + m + '月' + t + '日' + weekday[d] + '; 现在的时间是' + h + ':' + i + ':' + s; 
		t=setTimeout('startTime()',1000); 
	} 
	
	function checkTime(i){ 
		if (i<10){ 
			i='0'+i; 
		} 
		return i; 
	} 
</script> 

<body οnlοad='startTime()'>
	<div id='txt'></div>
	<br><br>
</body>

 

详细参考: http://www.w3school.com.cn/js/jsref_obj_date.asp

 

 

 

32、jquery 操作 radio

 

检测单个radio是否选中

 


<script src="http://code.jquery.com/jquery-latest.js"></script>  
	<script type="text/javascript">
	$(function(){
		if($('input[name=Number]').attr('checked')){
			// do something
		}else{
			// do something
		}
	})
	</script> 

    <input name="Number" type="radio" value="50">50


 

检测多个radio是否选中

 


<script src="http://code.jquery.com/jquery-latest.js"></script>  
	<script type="text/javascript">
	$(function(){
		if($('input[name=Number_of_Employees]:checked').length  != 1){
			// do something
		}else{
			// do something
		}
	})
	</script>  
    
    <input name="Number" type="radio" value="50">50
    <input name="Number" type="radio" value="250">250
    <input name="Number" type="radio" value="40">450

获取radio的值

 


<script src="http://code.jquery.com/jquery-latest.js"></script>  
	<script type="text/javascript">
	$(function(){
		alert($('input[name=Number]:checked').val());
	})
	</script>  
    
    <input name="Number" type="radio" value="50">50
    <input name="Number" type="radio" checked="checked" value="250">250
    <input name="Number" type="radio" value="40">450


 

点击层选中复选框

 

<script>
$(function(){
       $('#ecard li').click(function(){
              $(this).find(':checkbox').attr('checked',true);
       });
})
</script>

 

JavaScript版

 

 

<title>JavaScript 获取复选框的值</title>
<script>
function checkbox()
{
var str=document.getElementsByName("box");
var objarray=str.length;
var chestr="";
for (i=0;i<objarray;i++)
{
  if(str[i].checked == true)
  {
   chestr+=str[i].value+",";
  }
}
if(chestr == "")
{
  alert("请先选择复选框~!");
}
else
{
  alert("复选框的值是:"+chestr);
}
}
</script>
选择您的拿手技术:
  <input type="checkbox" name="box" id="box1" value="ASP" />ASP
  <input type="checkbox" name="box" id="box2" value="PHP" />PHP
  <input type="checkbox" name="box" id="box3" value="JSP" />JSP
  <input type="button" name="button" id="button" οnclick="checkbox()" value="提交" />

 

33、双击滚屏

 

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>双击滚屏</title>
<style>
	body { color: #FFFFFF; font-family: Verdana; font-size: 9pt }
</style>

<script language=JavaScript>
	var currentpos,timer;

	function initialize(){
		timer=setInterval("scrollwindow()",10);
	}

	function sc(){
		clearInterval(timer);
	}

	function scrollwindow(){
		currentpos=document.body.scrollTop;
		window.scroll(0,++currentpos);
		if (currentpos != document.body.scrollTop)
		sc();
	}

	document.οnmοusedοwn=sc
	document.οndblclick=initialize
</script>

</head>

<body bgcolor="#0496DC">
	<p align="center">请双击</p>
	<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p>
	<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p>
	<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p>
	<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p>
	<p>1</p><p>2</p><p>3</p><p>4</p><p>5</p><p>6</p><p>7</p><p>8</p><p>9</p><p>10</p>
</body>
</html>

 

34、框架显示/隐藏

 

<HTML>
<HEAD>
<TITLE>框架显示/隐藏</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</style>
<SCRIPT>
function switchSysBar(){
	if (switchPoint.innerText==3){
		switchPoint.innerText=4
		document.all("frmTitle").style.display="none"
	}
	else{
		switchPoint.innerText=3
		document.all("frmTitle").style.display=""
	}
}
</SCRIPT>
</HEAD>
<BODY bgColor="skyblue" scroll="no" style="MARGIN: 0px">
<TABLE border=0 cellPadding=0 cellSpacing=0 height="100%" width="100%">
  <TBODY>
    <TR> 
      <TD bgColor=#eeeeee align=middle id=frmTitle noWrap vAlign=center name="fmTitle">
		<IFRAME frameBorder=0 id=left name=left src="about:blank" style="HEIGHT: 100%; VISIBILITY: inherit; WIDTH: 145px; Z-INDEX: 2"></IFRAME> 
      <TD style="WIDTH: 10pt"> <TABLE border=0 cellPadding=0 cellSpacing=0 height="100%">
          <TBODY>
            <TR> 
              <TD οnclick=switchSysBar() style="HEIGHT: 100%"><SPAN class=navPoint 
            id=switchPoint title=关闭/打开左栏>fasdf3</SPAN></TD>
            </TR>
          </TBODY>
        </TABLE></TD>
      <TD style="WIDTH: 100%"><IFRAME frameBorder=0 id=frmright name=frmright 
      scrolling=no src="/index.html" 
      style="HEIGHT: 100%; VISIBILITY: inherit; WIDTH: 100%; Z-INDEX: 1"> </IFRAME></TD>
    </TR>
  </TBODY>
</TABLE>
</BODY>
</HTML>

35、JavaScript中的var_dump

 


<script>

 function var_dump(obj) {
  if(typeof obj == "object") {
     return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
  } else {
     return "Type: "+typeof(obj)+"\nValue: "+obj;
  }
}//end function var_dump
 
var name = 'demo';
alert(var_dump(name));

</script>


36、为 JavaScript 添加 in_array  支持二维数组


<script type="text/javascript">

function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            
			}
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                
				return true;
            }
        }
    }
     return false;
}

if(in_array('Kevin', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'})){
	alert(1);
}else{
	alert(0);
}
</script>

 

37、支持div的抖动

 

<style type="text/css">
#body{
	text-align:center;
}

#test{
	width:200px;
	position:absolute;
	margin:10px auto;
	height:100px;
	border:2px dotted red;
	text-align:center;
}
</style>

<body>
	<div style="margin:10px 200px">
		<div> <input type="button" value="开始抖动吧" οnclick="nn.start()" /></div>
		<div> <input type="button" value="停止抖动" οnclick="nn.stop()" /></div>
		<div id="test">
			<br>
			<a href="http://www.csscss.org">this is a test</a><br>
			<a href="http://www.csscss.org">this is a test</a><br>
			<a href="http://www.csscss.org">this is a test</a><br>
		</div>
	</div>
</body>

<script type="text/javascript">
	var m = document.getElementById("test");
	function SKclass (obj,Rate,speed) {
		var oL = obj.offsetLeft;
		var oT = obj.offsetTop;
		this.stop = null;
		this.oTime = null;
		var range = 0;
		var om = this;

		this.start=function(){
			if(parseInt(obj.style.left)==oL-2){
				obj.style.top=oT+2+"px";
				setTimeout(function(){obj.style.left=oL+2+"px"},Rate)
			}
			else
			{
				obj.style.top=oT-2+"px";
				setTimeout(function(){obj.style.left=oL-2+"px"},Rate)
			}
			
			range++;

			if(range < 7){
				this.oTime=setTimeout(function(){om.start()},speed);
			}else{
				clearTimeout(this.oTime);
				range = 0;
			}
		}

		this.stop=function(){
			clearTimeout(this.oTime);
		}
	}
	var nn=new SKclass(m,20,70);
</script>

38、JavaScript中的empty();

 

function empty (mixed_var) {
    var key;    
    if (mixed_var === '' ||
        mixed_var === ' ' ||        
        mixed_var === 0 ||
        mixed_var === '0' ||
        mixed_var === null ||        
		mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    } 
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }        return true;
    }
 
    return false;
}

 

39、input or area 显示/隐藏 提示信息

 

// <input type="text" value="密碼" οnclick="clearText(this,'密碼')" />




function clearText (el,message){
	var obj = el;
	if(typeof(el) == "string")
		obj = document.getElementById(id);
	if(obj.value == message){
		obj.value = "";
	}
	obj.onblur = function(){
		if(obj.value == ""){
			obj.value = message;
		}
	}
}

 

function clearArea (el,message){
	var obj = el;
	obj.style.borderColor = "#3399cc";
	if(obj.innerHTML == message){
		obj.innerHTML= "";
	}
	obj.onblur = function(){
		obj.style.borderColor = "#999999";
		if(obj.innerHTML == ""){
			obj.innerHTML = message;
		}
	}
}


40、 str_replace

 

function str_replace (search, replace, subject, count) {
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

 

41、 implode / explode

 

function implode (glue, pieces) {
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'

    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}


function explode (delimiter, string, limit) {

    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}


42、 全选

 

// select all 

	$("#clickAll").click(function() {
	   if($("#clickAll").attr("checked")){
		 $("input[name='checkbox']").each(function(){this.checked=true}); 
	   }else{
		 $("input[name='checkbox']").each(function() { $(this).attr("checked", false); });          
	   }
	});

 

43、去除数组中的重复项

 

<script>
Array.prototype.unique = function(){
    var a = [];
    var l = this.length;
    for (var i = 0; i < l; i++) {
        for (var j = i + 1; j < l; j++) {
            if (this[i] === this[j])
                j = ++i;
        }
        a.push(this[i]);
    }
    return a;
};

// Usage :
var uniqueA = [1,2,3,3,5,5,3,7];
var uniqueResult = uniqueA.unique(); 
// uniqueResult = [1, 2, 5, 3, 7];

</script>

44、用JavaScript动态加载CSS和JS文件

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <meta name="keywords" content="" />
        <meta name="Description" content="" />
        <title>动态加载CSS、JS文件</title>
    </head>
    <body>
        <script type="text/javascript">
            var dynamicLoading = {
                css: function(path){
					if(!path || path.length === 0){
						throw new Error('argument "path" is required !');
					}
					var head = document.getElementsByTagName('head')[0];
                    var link = document.createElement('link');
                    link.href = path;
                    link.rel = 'stylesheet';
                    link.type = 'text/css';
                    head.appendChild(link);
                },
                js: function(path){
					if(!path || path.length === 0){
						throw new Error('argument "path" is required !');
					}
					var head = document.getElementsByTagName('head')[0];
                    var script = document.createElement('script');
                    script.src = path;
                    script.type = 'text/javascript';
                    head.appendChild(script);
                }
            }
            dynamicLoading.css("test.css");
	    dynamicLoading.js("test.js");
        </script>
    </body>
</html>

45、用JavaScript生成菜单树(build_file_tree) 需要得到JSON

 


function build_file_tree(files) 
{
	var tree = $('<ul>');
	for (x in files) 
	{
		if (typeof files[x] == "object") 
		{
			var span = $('<span>').html(x).appendTo( $('<li>').appendTo(tree).addClass('folder') );
			var subtree = build_file_tree(files[x]).hide();
			
			span.after(subtree);
			span.click(function() { $(this).parent().find('ul:first').toggle(); });
		} else {
			$('<li>').html(files[x]).appendTo(tree).addClass('file');
		}
	}
	return tree;
}


 

实例:

 

<? $files = array(
			   'libraries' => array
			   (
				   'benchmark.html',
				   'config.html',
				   'database' => array
					   (
						 'active_record.html',
						 'binds.html',
						 'configuration.html',
						 'connecting.html',
						 'examples.html',
						 'fields.html',
						 'index.html',
						 'queries.html'
						),
				   'email.html',
				   'file_uploading.html',
				   'image_lib.html',
				   'input.html',
				   'language.html',
				   'loader.html',
				   'pagination.html',
				   'uri.html'
				)
			);
	$files = json_encode($files);
?>
<style type="text/css">
	body {
		font: 14px/18px Arial;
	}
	.folder {
		background-image: url(folder.png);
		background-repeat: no-repeat;
	}
	.file {
		background-image: url(file.png);
		background-repeat: no-repeat;	
	}
	ul {
		list-style: none;
		padding-left: 20px;
		cursor: pointer;
	}
	li{
		padding-left: 20px;
		margin: 2px;
	}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{
	var files = <?=$files?>;
	var file_tree = build_file_tree(files);
	file_tree.appendTo('#files');
	
	function build_file_tree(files) 
	{
		var tree = $('<ul>');
		for (x in files) 
		{
			if (typeof files[x] == "object") 
			{
				var span = $('<span>').html(x).appendTo( $('<li>').appendTo(tree).addClass('folder') );
				var subtree = build_file_tree(files[x]).hide();
				
				span.after(subtree);
				span.click(function() { $(this).parent().find('ul:first').toggle(); });
			} else {
				$('<li>').html(files[x]).appendTo(tree).addClass('file');
			}
		}
		return tree;
	}
});

</script>

<div id="files"></div>

 

46、textarea自动适应高度

 

<textarea style="overflow-y:hidden; height:20px;" 
	onpropertychange="this.style.height = (this.scrollHeight+3) + 'px'" 
	οninput="this.style.height = (this.scrollHeight+3) + 'px'">
</textarea>