Home > Javascript > Must Have funções em JavaScript

Must Have funções em JavaScript

JavaScript não vem com funções pré-empacotado ou métodos que podem executar operações especiais. Nós, como um programador tem de escrever essas funções. Neste artigo eu estou listando as funções javascript poucos que tenho encontrado.

Carregando o arquivo XML no 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);
         retorno xmlDoc;
     ( document. implementation && document. implementation . createDocument ) { ) Else document. execução (se & & documento. Implementação. CreateDocument) (
         / / Para Mozila
         . createDocument ( "" , "" , null ) ; = Documento xmlDoc. Implementação. CreateDocument ("", "", null);
         false ; xmlDoc. async = false;
         xmlFilePath ) ; xmlDoc. carga (xmlFilePath);
         retorno 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. loadXML (xmlString);
         retorno xmlDoc;
       ( document. implementation && document. implementation . createDocument ) { ) Else document. execução (se & & documento. Implementação. CreateDocument) (
          / / Para Mozila
          DOMParser ( ) ; DOMParser parser = new ();
          ( xmlString , "text/xml" ) ; xmlDoc = analisador. parseFromString (xmlString, "text / xml");
          retorno xmlDoc;
       )
 ) 

Trim conteúdo da string em JavaScript:

  str ) { função trim (str) (
      newstr var;
      ( /^\s*/ , "" ) . replace ( /\s*$/ , "" ) ; newstr = str. replace (/ ^ \ s * /, ""). replace (/ \ s * $ / ");
      ( /\s{2,}/ , " " ) ; newstr = newstr. replace (/ \ s (2) / ",");
      newstr retorno;
 ) 

Seu email:


Obter posição DIV em JavaScript:

  obj ) { getPosition function (obj) (
     0 , leftValue = 0 ; TopValue var = 0, leftValue = 0;
     obj ) { while (obj) (
          ; LeftValue + = obj. OffsetLeft;
          ; TopValue + = obj. OffsetTop;
          ; obj = obj. offsetParent;
     )
      "," + topValue ; finalvalue = leftValue + "," + TopValue;
      finalvalue retorno;
 ) 

Verifique se o valor digitado 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 ; } função IsNumeric (sText) (var ValidChars = "0123456789"; IsNumber var = true; Char var; for (i = 0; sText i <. comprimento; i + +) (chardata = sText. charAt (i); if (ValidChars . chardata indexOf () == - 1) (IsNumber = false break;;)) return IsNumber;) 

Verifica se os caracteres especiais em determinado valor:

  data ) { chkCharacter função (dos dados) (
        false ; var sucesso = false;
        "!@#$%^&*()+=-[] \\ \' ;,./{}| \" :<>?~" ; iChars "!@#$%^&*()+=-[] var = \ ';,./{}| \ ":<>?~"; 
        var i = 0 ; i < data. length ; i ++ ) { for (var i = 0; <i dados. comprimento; i + +) (
             iChars. indexOf ( data. charAt ( i ) ) != - 1 ) { if (iChars. indexOf (data. charAt (i))! = - 1) (
                    ; sucesso = true;
                    break;
             )
         )
         sucesso de retorno;
 ) 

Delete todas as linhas da tabela, exceto primeira linha:

  tableName ) { função tableName (clearTable) (
      document. getElementById ( tableName ) . rows . length ; = LastRow documento var. GetElementById (tableName). Fileiras. 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 objeto XML para XML String Conteúdo:

  / / Funciona apenas no navegador Mozilla Firefox
 xmlObj ) { função xmlToString (xmlObj) (
       new XMLSerializer ( ) ) . serializeToString ( xmlObj ) ; retorno (XMLSerializer new ()). serializeToString (xmlObj);
 ) 

String.replaceAll em JavaScript:

  = function ( pcFrom , pcTo ) { String. Protótipo. ReplaceAll = function (pcFrom, pcTo) (
          this . indexOf ( pcFrom ) ; var i = isso. pcFrom indexOf ();
          this ; var c = this;
          i > - 1 ) { while (i> - 1) (
              ( pcFrom , pcTo ) ; c. c = replace (pcFrom, pcTo);
              ( pcFrom ) ; i = c. indexOf (pcFrom);
          )
          retorno c;
       ) 

Esconder DIV SPAN / em JavaScript:

  divObj ) { hideDiv função (divObj) (
         divObj ) . style . display = "none" ; documento. getElementById (divObj). estilo. display = "none";
 ) 

Mostrar DIV SPAN / em JavaScript:

  divObj ) { showDiv função (divObj) (
        divObj ) . style . display = "inline" ; documento. getElementById (divObj). estilo. display = inline ";
 ) 

Verifica se os caracteres do alfabeto entrou pela primeira vez é em JavaScript:

  content ) { chkSpecial função (conteúdo) (
      ! ( ( content. charAt ( 0 ) . search ( /[az]+/ ) > - 1 ) || ( content. charAt ( 0 ) . search ( /[AZ]+/ ) > - 1 ) ) ) { if (! ((content. charAt (0). pesquisas (/ [az] + />) - 1) | | (content. charAt (0). pesquisas (/ [AZ] + />) - 1))) (
         "Please! enter the name that start with character." ) ; alert ("Por favor! digite o nome que começa com o personagem.");
      )
 ) 

Remova todos os espaços entre palavras em JavaScript:

  content ) { removeWhiteSpace função (conteúdo) (
     ( /\s/g , "" ) ; conteúdo de retorno. replace (/ \ s / g, "");
 ) 


Custom Search

Artigos populares:

Compartilhe e Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Tags: Categorias: Javascript Tags:
  1. Erol
    30 de dezembro de 2008 às 13:16 | # 1

    Verifique se o valor digitado contém dados numéricos:
    IsNumeric retorna ('.') verdade, mas é. (Ponto) um número?

  2. 30 de dezembro de 2008 às 17:45 | # 2

    Isso pode simplificar um pouco as coisas para "Verifique se o valor digitado contém dados numéricos":

     função IsNumeric (s) (
         retorno \ / ^ d + \. "\ d $ * /. teste (s);
     )
    

  3. 30 de dezembro de 2008 às 22:15 | # 3

    Brain Oi,
    Isso é ótimo com esta comunidade de desenvolvedores só vai saber o poder de expressão regular em vez da abordagem tradicional.

  4. 30 de dezembro de 2008 às 22:17 | # 4

    Erol Oi,
    Eu não percebi que havia (.) Dot verificar dentro numérico. Ter que remover. Obrigado por informar o mesmo.

  5. Neil
    30 de dezembro de 2008 às 23:51 | # 5

    Um, porque não isNaN?

  6. 31 de dezembro de 2008 às 08:28 | # 6

    Basta usar um framework (MooTools ou Prototype). A maioria deles é feita em um quadro.

  7. 31 de dezembro de 2008 às 10:43 | # 7

    Oi. Nice conjunto de funções. O showDiv função () provavelmente deve definir o 'display' de propriedade de "bloco" e não "inline", desde divs são elementos tradicionalmente nível de bloco.

  8. Strx
    2 de janeiro, 2009 às 02:52 | # 8

    Com Regexp jQuery +, todas essas funções === uma única linha de código

  9. Harry
    3 de fevereiro de 2009 às 03:23 | # 9

    Oi,
    Enquanto um arquivo xml em loadin script (primeira função), estou recebendo um erro "segurança" na xmldoc.Load (xmlFilePath); declaração .. Eu suponho que é por causa do caminho do arquivo ... eu tentei tanto absolutos como relativos caminhos .. pls alguém pode me ajudar com isso .. Como deve ser o meu ath xmlFileP?, se eu posso dar apenas nome do arquivo, então onde estaria o meu arquivo xml ser localizado .. (I pode parecer idiota aqui, mas realmente preciso disso) ...
    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
    Agradecemos a sua ajuda aqui

  1. Não trackbacks ainda.