Jan 132013
 

Come abbiamo visto nel post precedente possiamo leggere il contenuto di un attributo data-introdotto da html5.

Possiamo, ovviamente, anche scrivere i nostri contenuti tramite jQuery.

Partiamo dall’html del post precedente leggermente modificato:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Using data() for HTML5 data- attributes</title>
</head>
<body>
<p id="test-data">Paragrafo contenitore</p>
<button id="scrivi">Scrivi</button>
<button id="leggi">Leggi</button>
<script src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script>
...
</script>
</body>
</html>

La funzione per leggere è la medesima del post precedente, per scrivere invece useremo sempre il metodo data e passeremo due valori separati da virgola, il primo sarà il nome dell’attributo da aggiungere a data- e il secondo il valore:


$(document).ready(function() {
$('#leggi').click(function() {
alert('Contenuto: ' + $('#test-data').data('mioattributo'));
});
$('#scrivi').click(function() {
$('#test-data').data('mioattributo','prova');
});
});

L’esempio

Sorry, the comment form is closed at this time.