Javascript引号循环 - 完成后跳转到第一个

时间:2016-07-04 09:45:49

标签: javascript jquery html css

我遇到了脚本问题,因为一旦所有子元素循环通过,我就无法返回第一个元素。

https://jsfiddle.net/pad5bp0o/2/



$(document).ready(function() {
  var length = $("#tips li").length;
  var old = 0;

  function show() {
    var news = getRan();
    $("#tips li").hide();
    $("#tips li:nth-child(" + news + ")").fadeIn("fast");
    old++;
  };

  function getRan() {
    var news = old + 1;
    if (news < length) {
      return news;
    } else {
      var news = 0 + 1;
      return news;
      old++;
    }
  };

  show();
  $("#something").html(length);
  setInterval(show, 1000);

});
&#13;
#tips,
#tips li {
  margin: 0;
  padding: 0;
  list-style: none;
}

#tips {
  width: 250px;
  font-size: 16px;
  line-height: 120%;
}

#tips li {
  padding: 20px;
  background: #e1e1e1;
  display: none;
  /* hide the items at first only */
}

.active {
  opacity: 1;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="tips">
  <li>... if you want to become a better coder you need to eat your vegetables?</li>
  <li>... it takes more time to code a web page then to make a pizza?</li>
  <li>... you should validate your code?</li>
  <li>... jQuery is your friend? For real!</li>
  <li>... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>
<div id="something"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

一旦到达最后一个元素,您需要重置old变量。

function getRan() {
    var news = old + 1;
    if (news <= length) {
        return news;
    }

    news = 1;
    old = 0;
    return news;
};

DEMO

答案 1 :(得分:1)

一旦达到限制(old),将变量(1)重置为初始值(5)。

您还可以简化以下功能。 Updated fiddle

&#13;
&#13;
$(document).ready(function() {
  var length = $("#tips li").length;
  var old = 1;

  function show() {
    $("#tips li").hide();
    $("#tips li:nth-child(" + old + ")").fadeIn("fast");
    if (old == length) {
      old = 1;
    } else {
      old++;
    }
  };

  show();
  $("#something").html(length);
  setInterval(show, 1000);

});
&#13;
#tips,
#tips li {
  margin: 0;
  padding: 0;
  list-style: none;
}
#tips {
  width: 250px;
  font-size: 16px;
  line-height: 120%;
}
#tips li {
  padding: 20px;
  background: #e1e1e1;
  display: none;
  /* hide the items at first only */
}
.active {
  opacity: 1;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="tips">
  <li>1. ... if you want to become a better coder you need to eat your vegetables?</li>
  <li>2. ... it takes more time to code a web page then to make a pizza?</li>
  <li>3. ... you should validate your code?</li>
  <li>4. ... jQuery is your friend? For real!</li>
  <li>5. ... no matter what some people claim, you can't learn CSS in 3 hours?</li>
</ul>
<div id="something"></div>
&#13;
&#13;
&#13;