按时间间隔链接相似元素修改

Chaining similar elements modification by time interval

本文关键字:相似 元素 修改 链接 时间      更新时间:2023-09-26

我的html代码中有一个给定的p元素列表。在页面加载时,我尝试按给定的时间间隔(1秒)对每个<p>元素内容的修改进行排队。

给定html:

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

CSS:

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

既然我想连锁修改,JS应该是什么从字面上看:首先修改CSS/HTML的第一个p句子,1秒后替换第2行,1秒再替换第3行,4秒再修改第4行,等等。

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

那是失败(小提琴)。

我做错了什么?我应该使用for循环each()而不是选择器+setInterval吗?请转发关键词,以便我可以在相关文档中挖掘。Fiddle赞赏~

试试这个

$(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);
});

点击此处查看现场演示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

演示:http://jsbin.com/otevif/1/

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

您的间隔正在使用append而不是text来查看效果。使用document.ready而非$("p").ready

实时演示

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

实时演示

  i = 0;
$(document).ready(function () {
    div1 = $('#div1');
    parry = $("p");
    setInterval(function () {
        div1.append(parry.eq(i++).text() + '<br />')
        if (i > 3) i = 0;
    }, 400);
});