在纯JavaScript中逐个删除childElements

时间:2015-06-19 03:18:20

标签: javascript settimeout removechild

我有:

window.onload = function(){
    alerts = document.getElementById( 'alerts' );
    if( alerts ){
        alert = alerts.getElementsByClassName( 'alert' );
        setTimeout( function(){
            for( var i=0; i < alert.length; i++ ){
                ( function( i ){
                    setTimeout( function(){
                        alerts.removeChild( alert[i] );
                    }, 500);
                }
                )(i);
            }
        }, 4000);
    }
}

并希望在纯JavaScript 中以 500毫秒的间隔逐个删除这些警告 4000 ms

我有这个:

setTimeout

我认为这不是使用procedure TForm1.OnFunctionEval_ConnectForm(info: TProgramInfo); var c:TComponent; begin c := Application.FindComponent(Info.ParamAsString[0]); if not (c is TForm) then Info.ResultAsVariant := Null else Info.ResultAsVariant := TdwsRTTIVariant.FromObject(c); end; 的正确方法。

2 个答案:

答案 0 :(得分:1)

getElementsByClassName返回live collection,这意味着当在dom中移除或更改所选元素时,引用的集合也会更改。

因此,在您的示例中,当您启动alert时有2个elemnet,但是当第一个元素被移除时,alert将只有1个元素,但您指的是alert[1]未定义。

所以解决方法是从数组中删除第一个元素。

window.onload = function() {
  var alerts = document.getElementById('alerts');
  if (alerts) {
    alert = alerts.getElementsByClassName('alert');
    setTimeout(function() {
      for (var i = 0; i < alert.length; i++) {
        (function(i) {
          setTimeout(function() {
            alerts.removeChild(alert[0]);
          }, i * 500); //need increasing timeouts
        })(i);
      }
    }, 4000);
  }
}
<div id="alerts">
  <div class="alert">alert 1</div>
  <div class="alert">alert 2</div>
</div>

但你可以使用setInterval()以更好的方式解决这个问题,比如

window.onload = function() {
  var alerts = document.getElementById('alerts');
  if (alerts) {
    var alert = alerts.getElementsByClassName('alert');
    setTimeout(function() {
      var interval = setInterval(function() {
        alerts.removeChild(alert[0]);
        if (!alert.length) {
          clearInterval(interval)
        }
      }, 1000);
    }, 3000);
  }
}
<div id="alerts">
  <div class="alert">alert 1</div>
  <div class="alert">alert 2</div>
</div>

答案 1 :(得分:1)

更简单的方法是使用setInterval

window.onload = function() {
  alerts = document.getElementById('alerts');
  if (alerts) {
    alert = alerts.getElementsByClassName('alert');
    var interval = setInterval(function() {
      if (alert.length) {
        alerts.removeChild(alert[alert.length - 1]);
      } else {
        clearInterval(interval);
      }

    }, 4000);
  }
}
<div id="alerts">
  <div class="alert">alert 1</div>
  <div class="alert">alert 2</div>
</div>