1秒后删除所有课程纯Javascript

时间:2017-11-26 23:07:29

标签: javascript

我尝试在1秒后删除所有类但这不起作用,代码如下:



div.post

function showTooltip (d, i) {

    //Save the chosen circle (so not the voronoi)
    var element = d3.selectAll(".countries."+d.CountryCode);

    //Define and show the tooltip
    $(element).popover({
        placement: 'auto top',
        container: '#chart',
        trigger: 'manual',
        html : true,
        content: function() {
            return "<span style='font-size: 12px; text-align: center;'>" + "<span>" + "Speaker: " + "</span>" + d.Speaker + "\n"
            + "<span>" + "Duration: " + "</span>" + Math.round(d.Duration) + "\n" +"</span>"; }
    });
    $(element).popover('show');

    //Make chosen circle more visible
    element.style("opacity", 1)
        .style("stroke-width", 6);
&#13;
function copyLink() {
  var text = document.getElementsByClassName("text"),
      len = text.length;
  for(i = 0; i < len; i++) {
      text[i].classList.add("copied");
      setTimeout(function() {
        text[1].classList.remove("copied");
      },1000);
  }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:-1)

问题

循环在超时回调开始之前完成执行,因此当它们被执行时,i变量对于所有这些变量都是len - 1

ES6方法

如果您正在使用ES6,则可以将var更改为let。 所以它看起来像这样:

for(let i = 0; i < len; i++) {
    setTimeout(function() {
        text[i].classList.remove("copied");
    }, 1000);
}

ES5方法

如果您的应用仅使用ES5,则解决您问题的唯一方法是创建新范围并在其中插入setTimeout

使用catch块创建新范围

for(var i = 0; i < len; i++) {
    try { throw i; } catch(i) {
        setTimeout(function() {
            text[i].classList.remove("copied");
        }, 1000);
    }
}

使用IIFE创建新范围

for(var i = 0; i < len; i++) {
    (function(i) {
        setTimeout(function() {
            text[i].classList.remove("copied");
        }, 1000);
    })();
}

使用函数调用创建新范围

for(var i = 0; i < len; i++) {
    loopCallBack(i);
}

function loopCallBack(i) {
    setTimeout(function() {
        text[i].classList.remove("copied");
    }, 1000);
}

完整ES5示例

&#13;
&#13;
function copyLink() {
  var text = document.getElementsByClassName("text"),
    len = text.length;
  for (var i = 0; i < len; i++) {
    (function(i) {
      text[i].classList.add("copied");
      setTimeout(function() {
        text[i].classList.remove("copied");
      }, 1000);
    })(i);
  }
}
&#13;
.copied {
  color: red;
}
&#13;
<p class="link text">Text</p>

<p class="demo text">Some text</p>

<a href="javascript:copyLink()">Click me</a>
&#13;
&#13;
&#13;

不同的方法

您可以在setTimeout回拨

中添加for循环,而不是为每次迭代创建新范围

&#13;
&#13;
function copyLink() {
  var text = document.getElementsByClassName("text"),
    len = text.length;
  for (var i = 0; i < len; i++) {
    text[i].classList.add("copied");
  }
  setTimeout(function() {
    for (var i = 0; i < len; i++) {
      text[i].classList.remove("copied");
    }
  }, 1000);
}
&#13;
.copied {
  color: red;
}
&#13;
<p class="link text">Text</p>

<p class="demo text">Some text</p>

<a href="javascript:copyLink()">Click me</a>
&#13;
&#13;
&#13;