Lezione #id-jq-2013-0017#
JQuery ci permette di ottenere i dati del nostro documento HTML, in particolare testo – Metodo text() -, tag HTML – Metodo html() -, valori dei Form. – Metodo val() –.
Metodo: text() -> restituisce il contenuto in formato testo dell’elemento selezionato
Vediamo il seguente codice:
1 2 3 | $( "#btn1" ).click( function (){ alert( "Text: " + $( "#test" ).text()); }); |
Metodo: html() -> restituisce il contenuto in formato HTML dell’elemento selezionato
Vediamo il seguente codice:
1 2 3 | $( "#btn2" ).click( function (){ alert( "HTML: " + $( "#test" ).html()); }); |
Metodo: val() -> restituisce il contenuto di un campo di input selezionato
Vediamo il seguente codice:
1 2 3 | $( "#btn3" ).click( function (){ alert( "Valore: " + $( "#test2" ).val()); }); |
Metodo: attr() -> restituisce il contenuto di un attributo specifico
Vediamo il seguente codice:
1 2 3 | $( "#btn4" ).click( function (){ alert($( "#test3" ).attr( "href" )); }); |
Mettiamo insieme il tutto in un unico listato:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <!DOCTYPE html> <html> <head> <title>Titolo del documento</title> <script type= "text/javascript" src= "js/jquery-2.0.3.js" ></script> <script> $(document).ready( function (){ $( "#btn1" ).click( function (){ alert( "Text: " + $( "#test" ).text()); }); $( "#btn2" ).click( function (){ alert( "HTML: " + $( "#test" ).html()); }); $( "#btn3" ).click( function (){ alert( "Valore: " + $( "#test2" ).val()); }); $( "#btn4" ).click( function (){ alert($( "#test3" ).attr( "href" )); }); }); </script> </head> <body> <p id= "test" ><i>Questo è un</i> <strong>paragrafo</strong></p> Questo è un campo di input:<input type= "text" id= "test2" value= "Il contenuto del campo di Input" > <br><br> <br><br> <button id= "btn1" >Vedi Metodo text()</button> Restituisce il contenuto in formato testo. <br><br> <button id= "btn2" >Vedi Metodo html()</button> Restituisce il contenuto in formato HTML. <br><br> <button id= "btn3" >Vedi Metodo val()</button> Restituisce il contenuto del campo di Input. <br><br> <button id= "btn4" >Vedi Metodo attr()</button> Restituisce il valore di uno specifico attributo. </body> </html> |