开发者

How can alter text in a loop in a DIV

开发者 https://www.devze.com 2023-02-24 03:20 出处:网络
I have text inside a DIV tag.Is it possible to change the text content with five different text contents in cycle that never ends?Sounds simple, but I\'m trying to find the easiest approach with jquer

I have text inside a DIV tag. Is it possible to change the text content with five different text contents in cycle that never ends? Sounds simple, but I'm trying to find the easiest approach with jquery or related.

开发者_如何学Python

Many thanks, Erik


Really simple approach: use setInterval().

var text = ['foo', 'bar', 'baz'];
    i = 0,
    $div = $('#myDiv');

setInterval(function ()
{
    $div.text(text[i++ % text.length]);
}, 1000);

http://jsfiddle.net/mattball/TJv3K/


Edit If you want to get fancier with the effects: http://jsfiddle.net/mattball/TJv3K/1/


Edit 2 re OP comments (below)

  • Fix #1: use distinct variable names for each rotator, because variable scoping is unaffected by <script> tags.
  • Fix #2: don't change variable names, but use closures so that the global scope isn't polluted.

Other fixes needed (shown in both fiddles):

  • Actually load jQuery from somewhere, otherwise none of this code will work.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    
  • Remove the trailing comma at the end of the first text array literal

  • Change the semicolons following the two text array declarations to commas, otherwise the following variables (i and $div) will be declared as global, which is a bad thing.


Hard to say your intentions, but you can use setInterval to trigger a timer to append/change info in the div.

<div id="change">initial content</div>
<script>
    $(function() {
      setInterval(update, 1000);
    });

    function update() {
      $("#change").append(".");
    }
</script>

Working example


Here's an example: http://jsfiddle.net/jbkjE/11/. It's a bit bigger than this because I added some elements to display the clockwork that's happening.

Here's the code:

var strings = ['Foo', 'Bar', 'FooBar', 'BarFoo', 'FooBarFoo'];
var index = 0;

function cycle()
{
    $('#cycle').text(strings[index % strings.length]);
    index++;

    setTimeout(cycle, 500);
}

cycle();

You just cycle through the values of the array, and to do that, you modulo the length of the array (Google "modulo operator").

And a (kinda) one-liner:

var index = 0;
var strings = ['Foo', 'Bar', 'FooBar', 'BarFoo', 'FooBarFoo'];

$(function() { setInterval(function() {$('#cycle').text(strings[index++ % strings.length]);}, 1000); });
0

精彩评论

暂无评论...
验证码 换一张
取 消