search
HomeWeb Front-endJS Tutorialjs common functions 2008-8-16 finishing page 1/2_javascript skills

//js常用函数 更新2008-8-16 取自网络

function $(id) {
return document.getElementById(id);
}


/**************
Function: getElementsByClassName
Usage:
Get the hyperlink class in the document that is "info-links".
getElementsByClassName(document, "a", "info-links");
Get the class of p in the container which is col.
getElementsByClassName(document.getElementById("container"), "p", "col");
Get all classes in the document that are "click-me".
getElementsByClassName(document, "*", "click-me");
Returns an array
*******************/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "-");
var oRegExp = new RegExp("(^|s)" strClassName "(s|$)");
var oElement;
for(var i=0; ioElement = arrElements[i];
if(oRegExp.test(oElement.className))
arrReturnElements.push(oElement);
}
return (arrReturnElements)
}





/**************
replaceAll:
Replace characters in a string.
Usage:
yourstring.replaceAll("Character to be replaced", "Replace with what");
Example:
"cssrain".replaceAll("s", "a");
" cs sr ai n".replaceAll(" ", "");
*****************/
String.prototype.replaceAll = function (AFindText,ARepText){
raRegExp = new RegExp(AFindText,"g");
return this.replace(raRegExp,ARepText);
}


/**************
* Processing of spaces before and after strings.
* If you want to replace the spaces in the middle, please use the replaceAll method.
* Usage:
* " cssrain ".trim();
*****************/
String.prototype.trim=function()
{
return this.replace(/(^s*)|(s*$)/g,"");//将字符串前后空格,用空字符串替代。
}


/**************
* Calculate the real length of the string
//String has an attribute length, but it cannot distinguish between English characters.
//Calculate Chinese characters and full-width characters character. However, when storing data, Chinese characters and full-width characters are stored in two bytes.
//All require additional processing. I wrote a function myself to return the true length of String.
Usage:


*******************/
String.prototype.codeLength=function(){
var len=0;
if(this==null||this.length==0)
return 0;
var str=this.replace(/(^s*)|(s*$)/g,"");//去掉空格
for(i=0;iif(str.charCodeAt(i)>0&&str.charCodeAt(i)len ;
else
len =2;
return len;
}


//JS获取字符串的实际长度,用来代替 String的length属性
String.prototype.length = function(){
return this.replace(/[u4e00-u9fa5] /g,"**").length;
}

/**************
//Filter HTML
//In order to prevent users from submitting malicious scripts when commenting, you can first filter HTML tags and filter out double quotes and single quotes. Quotation marks, symbol &, symbol Usage:


*******************/
String.prototype.filterHtml=function(){
return this.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'");
}


/**************
format:
Formatting time.
Usage:
yourdate.format("your date format");
Example:
obj0 = new Date("Sun May 04 2008").format("yyyy-MM-dd" );
obj1 = new Date().format("yyyy-MM-dd hh:mm:ss");
obj2 = new Date().format("yyyy-MM-dd");
obj3 = new Date().format("yyyy/MM/dd");
obj4 = new Date().format("MM/dd/yyyy");
****** ********/
Date.prototype.format = function(format)
{
var o = {
"M " : this.getMonth() 1, //month
"d " : this.getDate(), //day
"h " : this.getHours(), //hour
"m " : this.getMinutes(), //minute
"s " : this.getSeconds(), //second
"q " : Math.floor((this.getMonth() 3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y )/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear() "").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("(" k ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00" o[k]).substr(("" o[k]).length));
return format;
}


/**************
형식:
형식 번호.
예:
var n = format_number( 123456.45656 , 2 ) // .toFixed(2) 또한 It 구현할 수 있지만 FF와 호환되지 않습니다.
alert(n)
*****************/
함수 format_number(str,digit)
{
if(isNaN(str))
{
alert("您传入的值不是数字! ");
0을 반환합니다.
}
else if(Math.round(digit)!=digit)
{
alert("您输入的小数位数不是整数!");
0을 반환합니다.
}
else
return Math.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit);
}

/**********양식 작업*********/

/**************
* 라디오 버튼의 선택된 값을 가져옵니다.
* 사용법:
*
*
*
*
*********************/
function getRadioValue(radioName){
var obj=document.getElementsByName (라디오이름);
for(var i=0;iif(obj[i].checked){
return obj[i].value;
}
}
}

/**************
* 체크박스 모두 선택/선택 취소/반전
* 사용법:

************ **/
function checkAll(form, sel) {
for (i = 0, n = form. elements.length; i if(form.elements[i].type == "checkbox") {
if(form.elements[i].checked == true)
form.elements[i].checked = (sel == "all" ? true : false);
} else {
form.elements[i].checked = (sel == "none" ? false : true);
}
}
}
}


/**************
* 체크박스가 선택되어 있는지 확인하세요.
* 아무것도 선택하지 않으면 false가 반환됩니다.
* 사용법:

*******************/
function SCheckBox(_formName,_checkboxName){
var selflag = {'checked':0,'cvalues':[]};
_scheckbox = eval('document.' _formName '.' _checkboxName);
if(_scheckbox){
if(eval(_scheckbox.length)){
for(i=0;i<_scheckbox.length>if(_scheckbox[i].checked ){
selflag.checked ;
selflag.cvalues.push(_scheckbox[i].value);
}
};
}else if(_scheckbox.checked){
selflag.checked ;
selflag.cvalues.push(_scheckbox.value);
}
if(selflag.checked){
return selflag;
}
}
false를 반환합니다.
}

//如果控件值=原来值则清空
functionclearInput(input){
if(input.value == input.defaultValue){
input.value = "";
}
}

/*****************양식 작업이 종료됩니다*************/


/**************/
//收藏到书签.(兼容IE와 FF)。

function addBookmark(title,url) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( document.all ) {
window.external.AddFavorite( url, title);
} else if( window.opera && window.print ) {
return true;
}
}

/************
기능: 텍스트 상자가 포커스 작업을 가져오거나 잃습니다.
텍스트 상자에서 검색할 때 이 방법이 자주 나타납니다.
텍스트에 "검색"이 표시된 후 사용자가 해당 텍스트를 마우스로 클릭하면
텍스트 상자의 내용이 지워집니다. 사용자가 내용을 입력하지 않으면 텍스트 값이 복원됩니다.
입력하면 사용자가 입력한 것으로 표시됩니다.
사용법:


*********************
函数 : 文本框得到与失去焦点 操작품.
这个方法经常常常常文本框搜索的时候出现。
文本里显示 “ 搜索 ”,然后当用户鼠标点击此文本,
文本框内填写,内容,那么文本的值又复原。
如果填写了,就显示用户填写的。
사용법:


************
기능: 마우스 클릭이 왼쪽인지 오른쪽인지 확인하는 데 사용됩니다. (IE 및 ff와 호환)
사용법:
onmousedown="mouse_keycode(event)"
*******************/
function clearTxt(id,txt) {
if (document.getElementById(id).value == txt)
document.getElementById(id).value="" ;
반환 ;
}
function fillTxt(id,txt) {
if ( document.getElementById(id).value == "" )
document.getElementById(id).value=txt;
반환 ;
}


/************
기능: 개체의 onclick 이벤트를 트리거합니다. (IE 및 FF와 호환)
사용법:


***********************
函数 : 用来判断鼠标按的是左键还是右键。(兼容IE와ff)
사용법:
onmousedown="mouse_keycode(event)"
***/
function mouse_keycode(event){
var event=event||window.event;
var nav=window.navigator.userAgent;
if (nav.indexOf("MSIE")>=1) //如果浏览器为IE.解释:因为 document.all 是 IE 的特有属性,所以通常用这个方法来判断客户端是否是IE浏览器,document.all?1:0;
{
if(event.button==1){alert("左键")}
else if(event.button==2){alert("右键")}
}
else if(nav.indexOf("Firefox")>=1) ////如果浏览器为Firefox
{
if(event.button==0){alert("左键");}
else if(event.button==2){alert("右键");}
}
else{ //如果浏览器为其他
alert("other" );
}
}


/***
函数 :触发某个对象的onclick事件。(兼容IE와FF)
사용법: ***/ function handerToClick(objid){ var obj=document.getElementById(objid); if(document.all){ obj.fireEvent("onclick"); }else{ var e=document.createEvent('MouseEvent'); e.initEvent('클릭',false,false); obj.dispatchEvent(e); } } /*** 实现按回车提交 ******************/
function QuickPost(evt,form){
var evt = window.event?window.event:evt;
if(evt.keyCode == 13){
document.getElementById(form).submit();
}
}


/***********
Verify if it is a number
**********/
function checkIsInteger( str)
{
//If it is empty, the check is passed
if(str == "")
return true;
if(/^(-?)(d ) $/.test(str))
return true;
else
return false;
}


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools