so come ciclo tra gli ingressi di seguito, alla ricerca di quelli con una specifica classe di "tester"jQuery - Looping attraverso elementi con specifico attributo
Ed ecco come lo faccio:
<input type='text' name='firstname' class="testing" value='John'>
<input type='text' name='lastname' class="testing" value='Smith'>
<script type="text/javascript">
$(document).ready(function(){
$.each($('.testing'), function() {
console.log($(this).val());
});
});
</script>
Emette "John", "Smith" come previsto.
Non voglio utilizzare lo class="testing"
e utilizzare un attributo personalizzato: testdata="John"
.
Quindi questo è quello che avrei fatto:
<input type='text' name='firstname' testdata='John'>
<input type='text' name='lastname' testdata='Smith'>
Il mio obiettivo è quello di popolare automaticamente i valori di ogni ingresso con tutto ciò che è dentro testdata
, ma solo quelle rilevate per avere l'attributo testdata
.
Questo è stato il mio tentativo fallito di usare la $.each
ciclo:
$.each($('input').attr('testdata'), function() {
var testdata = $(this).attr('testdata');
$(this).val(testdata);
});
ottengo questa risposta: Uncaught TypeError: Cannot read property 'length' of undefined
chiunque può vedere quello che sto facendo di sbagliato?
lato: utilizzare 'data-*' attributi, piuttosto che il proprio quelle composte. – ahren
È una pratica comune? Se è così, è bene sapere. Ovunque mi raccomando, posso leggere su questo? – coffeemonitor
Lo è sicuramente. Puoi leggere a riguardo http://ejohn.org/blog/html-5-data-attributes/ o http://html5doctor.com/html5-custom-data-attributes/ – ahren