js 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; 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;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 <, 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;i
return obj[i].value;
}
}
}
/**************
* 체크박스 모두 선택/선택 취소/반전
* 사용법:
************ **/
function checkAll(form, sel) {
for (i = 0, n = form. elements.length; i < n; 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;i ){
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;
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
