1

在下面的代码中,我尝试使用包含字符数组的value属性来创建具有“rot”类的对象来更改内部 HTML 。

我希望这些字符会间隔旋转。

我注意到问题出在内部for循环中 - 我需要一个setTimeout或类似的东西,但它不起作用。

这个问题的任何解决方案?

提前致谢。

<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>
4

1 回答 1

1

您可以使用 jQuery .data() 方法来存储正在旋转的每个字符的当前索引。此外, .each() 方法可以很容易地为 jQuery 结果中的每个元素执行某些功能。

尝试这个:

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);
于 2010-11-18T22:52:13.830 回答