Must Have funções em JavaScript
JavaScript não vem com pré-empacotado funções ou métodos que podem executar operações especiais. Nós, como um programador tem de escrever essas funções. Neste artigo eu estou alistando abaixo algumas funções em JavaScript que eu encontrei.
Carregando arquivo XML em JavaScript:
xmlFilePath ) { load_xml_file função (xmlFilePath) ( window. ActiveXObject ) { if (window. ActiveXObject) ( / / para o IE ActiveXObject ( "Microsoft.XMLDOM" ) ; xmlDoc = new ActiveXObject ( "Microsoft.XMLDOM"); false ; xmlDoc. async = false; xmlFilePath ) ; xmlDoc. carga (xmlFilePath); xmlDoc; ( document. implementation && document. implementation . createDocument ) { ) Else if (aplicação document. & & documento. Execução createDocument.) ( / / para Mozila . createDocument ( "" , "" , null ) ; documento xmlDoc =. execução. createDocument ( "", "", null); false ; xmlDoc. async = false; xmlFilePath ) ; xmlDoc. carga (xmlFilePath); xmlDoc; ) )
Carregando conteúdo XML String em JavaScript:
xmlString ) { load_xml_string função (xmlString) ( window. ActiveXObject ) { if (window. ActiveXObject) ( / / para o IE ActiveXObject ( "Microsoft.XMLDOM" ) ; xmlDoc = new ActiveXObject ( "Microsoft.XMLDOM"); "false" ; xmlDoc. async = "false"; xmlString ) ; xmlDoc. xmlString (loadXML); xmlDoc; ( document. implementation && document. implementation . createDocument ) { ) Else if (aplicação document. & & documento. Execução createDocument.) ( / / para Mozila DOMParser ( ) ; parser = new DOMParser (); ( xmlString , "text/xml" ) ; xmlDoc = analisador. parseFromString (xmlString, "text / xml"); xmlDoc; ) )
Trim String conteúdo em JavaScript:
str ) { function trim (str) ( newstr var; ( /^\s*/ , "" ) . replace ( /\s*$/ , "" ) ; newstr = str. replace (/ ^ \ s * /, ""). replace (/ \ s * $ /, ""); ( /\s{2,}/ , " " ) ; newstr = newstr. replace (/ \ s (2,) /, ""); newstr retorno; )
Getting DIV posição em JavaScript:
obj ) { getPosition function (obj) ( 0 , leftValue = 0 ; var topValue = 0, leftValue = 0; obj ) { while (obj) ( ; leftValue + = obj offsetLeft.; ; topValue + = obj offsetTop.; ; obj = obj offsetParent.; ) "," + topValue ; FinalValue = leftValue + "," topValue +; FinalValue retorno; )
Verificar se Entered Value contém dados numéricos:
sText ) { var ValidChars = "0123456789" ; var IsNumber = true ; var Char ; for ( i = 0 ; i < sText. length ; i ++ ) { charData = sText. charAt ( i ) ; if ( ValidChars. indexOf ( charData ) == - 1 ) { IsNumber = false ; break ; } } return IsNumber ; } function IsNumeric (sText) (var ValidChars = "0123456789"; var IsNumber = true; Char var; for (sText i = 0; i <comprimento.; i + +) (charData = sText. charAt (i); if (ValidChars . indexOf (charData) == - 1) (IsNumber = false; break;)) return IsNumber;)
Verifica se os caracteres especiais em Valor dados:
data ) { chkCharacter function (data) ( false ; var success = false; "!@#$%^&*()+=-[] \\ \' ;,./{}| \" :<>?~" ; iChars var = "!@#$%^&*()+=-[] \ \ \ ';,./{}| \ ":<>?~"; var i = 0 ; i < data. length ; i ++ ) { for (var i = 0; i <comprimento de dados.; i + +) ( iChars. indexOf ( data. charAt ( i ) ) != - 1 ) { if (iChars. indexOf (dados. charAt (i))! = - 1) ( ; sucesso = true; break; ) ) sucesso de retorno; )
Eliminar todas as linhas da tabela, exceto 1 ª linha:
tableName ) { função clearTable (tableName) ( document. getElementById ( tableName ) . rows . length ; lastRow var = documento. getElementById (tableName). linhas. comprimento; lastRow > 1 ) { if (lastRow> 1) ( i = lastRow - 1 ; i > 0 ; i -- ) { for (i = lastRow - 1, i> 0; i -) ( tableName ) . deleteRow ( i ) ; documento. getElementById (tableName) deleteRow. (i); ) ) )
Converter XML objeto para XML String Conteúdo:
/ / Funciona somente no navegador Mozilla Firefox xmlObj ) { função xmlToString (xmlObj) ( new XMLSerializer ( ) ) . serializeToString ( xmlObj ) ; return (XMLSerializer novo ()). serializeToString (xmlObj); )
String.replaceAll em JavaScript:
= function ( pcFrom , pcTo ) { String. Protótipo. ReplaceAll = function (pcFrom, pcTo) ( this . indexOf ( pcFrom ) ; var i = isso. indexOf (pcFrom); this ; var c = this; i > - 1 ) { while (i> - 1) ( ( pcFrom , pcTo ) ; C = c. replace (pcFrom, pcTo); ( pcFrom ) ; i = c. pcFrom indexOf (); ) return c; )
Esconder DIV / SPAN em JavaScript:
divObj ) { função hideDiv (divObj) ( divObj ) . style . display = "none" ; documento. getElementById (divObj). estilo. display = "none"; )
Mostrar DIV / SPAN em JavaScript:
divObj ) { função showDiv (divObj) ( divObj ) . style . display = "inline" ; documento. getElementById (divObj). estilo. display = "inline"; )
Verificar primeiro caractere digitado é Alphabet em JavaScript:
content ) { função de conteúdo (chkSpecial) ( ! ( ( content. charAt ( 0 ) . search ( /[az]+/ ) > - 1 ) || ( content. charAt ( 0 ) . search ( /[AZ]+/ ) > - 1 ) ) ) { if (! ((content. charAt (0). search (/ [az] + /)> - 1) | | (content. charAt (0). search (/ [AZ] + /)> - 1))) ( "Please! enter the name that start with character." ) ; alert ( "Por favor! digite o nome que começa com a personagem."); ) )
Remover todos os espaços entre palavras em JavaScript:
content ) { removeWhiteSpace função (conteúdo) ( ( /\s/g , "" ) ; índice de retorno. replace (/ \ s / g, ""); )

















Verificar se Entered Value contém dados numéricos:
IsNumeric ('.') retorna verdadeiro, mas é. (ponto) um número?
Isso pode simplificar um pouco as coisas para "Verifique se Entered Value contém dados numéricos":
Oi Brain,
Isso é ótimo com esta comunidade de desenvolvedores só vai saber o poder de expressão regular em vez da abordagem tradicional.
Oi Erol,
Eu não percebi que havia (.) Ponto de verificação dentro numérico. Ter que remover. Obrigado por nos informar o mesmo.
Um, porque não isNaN?
Basta usar um quadro (ou MooTools Prototype). A maioria deles é feito em um quadro.
Oi. Nice set de funções. O showDiv função () provavelmente deve definir a propriedade 'display' para 'bloco', em vez de 'inline', uma vez que são tradicionalmente divs elementos nível de bloco.
Com Regexp + jQuery, tudo isto === funções de uma única linha de código
Oi,
Enquanto loadin arquivo XML em um script (função 1), estou recebendo um erro de 'segurança' na xmlFilePath (xmlDoc.load); declaração .. Eu suponho que é por causa do caminho do arquivo ... eu tentei absolutos e relativos caminhos .. pls alguém pode me ajudar com isso .. Como deve ser a minha ath xmlFileP?, se eu posso dar apenas nome do arquivo, então onde é que o meu arquivo xml ser localizado .. (I pode parecer idiota aqui, mas realmente necessitam desta) ...
Eu só podia ver o erro como erro de 'segurança' usando JavaScript try-catch (e.Message), então não tenho certeza do que é a razão de erro de segurança
Aprecie a sua ajuda aqui