2010-11-01 3 views
1

Dans la partie ci-dessous du code j'ai essayé de faire les objets avec classe "rot" pour modifier le code HTML interne en utilisant l'attribut valeur qui comprend un tableau de caractères.Comment faire pivoter un tableau de valeurs dans une balise spécifique contenant une classe unique par intervalle dans jquery?

Je veux que ces caractères tournent avec un intervalle.

Je remarqué que le problème est dans le intérieur boucle - je besoin il un setTimeout ou quelque chose comme ça, mais ça ne fonctionne pas.

une solution à ce problème?

Merci d'avance.

<script src="http://code.jquery.com/jquery-latest.min.js"></script> 


<span class="rot" value="$^%^@">currency</span> 
<span class="rot" value="1^2^3">numbers</span> 


<script> 
function rotateItem() 
{ 
for(j=0;j<$(".rot").get().length;j++) 
{ 
    valueToRotate = $(".rot:eq("+j+")").attr("value").split("^"); 

    for(i=0;i<valueToRotate.length;i++) 
    { 
    $(".rot:eq("+j+")").html(valueToRotate[i]); 
    } 
} 
} 
setInterval("rotateItem()",1000) 
</script> 

Répondre

1

Vous pouvez utiliser la méthode jQuery .data() pour stocker l'index actuel de chaque caractère pivoté. De plus, la méthode .each() rend très facile l'exécution de certaines fonctions pour chaque élément d'un résultat jQuery.

Essayez ceci:

function rotateItem() { 
    $('.rot').each(function() { // for each jquery object with class 'rot' 
     var values = $(this).attr('value').split('^'); // get value array 

     if ($(this).data('activeVal') == null) // if 'activeVal' is not set, set it to a default of 0 
      $(this).data('activeVal', 0); 
     else // otherwise increment through array indexes 
      $(this).data('activeVal', ($(this).data('activeVal') + 1)%values.length); // mod (%) makes sure we loop back when we get to the end 

     $(this).html(values[$(this).data('activeVal')]); 
    }); 
} 

setInterval(rotateItem,1000); 
Questions connexes