Вопрос

I have a given list of p elements on my html code. On page load, I try to queuing modifications of each <p> elements's content by a given interval of time (1sec).

Given the html:

<p>I want to change first!</p>
<p>I want too!</p>
<p>Me 3rd !</p>
<p>Hey, don't forget me!</p>

the CSS:

p { padding: 2px 5px 0px 10px; }
.p { color: #999; }
.green { color:green; border-bottom: 1px solid #888; background: #EEE; }

What should be the JS to since I want to chain up modification. Literally: the first p sentence to be CSS / HTML modified first, 1sec later the 2nd line should be replaced, 1sec later the 3rd line, 4sec later the 4th line, etc.

$("p").ready(function(){
    setInterval(function () {
        $('p').text('aaaahhhhh.... happy!')
    }, 1000);
  });

That's fail (fiddle).

What I am doing wrong ? should I use a for loop, each(), instead of selector + setInterval ? please forward keywords so I may dig in the relevant docs. Fiddle appreciate~

Это было полезно?

Решение 3

    function modifyTargetDeferred(target) {
        target.first().text('ahhh... happy');
        if (target.length > 1) {
            setTimeout(function() {
                modifyTargetDeferred(target.not(':first'));
            }, 1000);
        }
    }

    setTimeout(function() {
        modifyTargetDeferred($('p'));
    }, 1000);

Другие советы

Try this

$(document).ready(function(){
    var st=null;
    var i=0;
    st=setInterval(function () {
        $('p').eq(i).text('aaaahhhhh.... happy!'); 
        if(i==$('p').length-1)// one less because i initialised by 0.
            clearTimeout(st);
        i++
    }, 1000);
});

Check live demo here http://jsfiddle.net/gT3Ue/14/

(function next($set, i) {
  setTimeout(function () {
    $set.eq(i).text('aaaahhhhh.... happy!');
    if (i < $set.length - 1) {
      next($set, i + 1); 
    }  
  }, 1000);
//    /\
//    ||------ the delay
}($('p'), 0));
//  /\    /\
//  ||    ||-- the starting index
//  ||----- -- your set of elements

demo: http://jsbin.com/otevif/1/

Your interval is working use append instead of text to see the effect. Use document.ready not $("p").ready

Live Demo

$(document).ready(function(){
    setInterval(function () {
        $('p').append('aaaahhhhh.... happy!')
    }, 1000);
  });

Live Demo

  i = 0;
$(document).ready(function () {
    div1 = $('#div1');
    parry = $("p");
    setInterval(function () {
        div1.append(parry.eq(i++).text() + '<br />')
        if (i > 3) i = 0;
    }, 400);
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top