使用jQuery在数组中到达最后一个元素时停止

时间:2017-08-01 07:37:17

标签: jquery arrays



$("#show").click(function() {
	var elem = $('#progress-text');
	count = 0;
	wordsArray = ["1", "2", "3", "Bye"];
	setInterval(function () {
		count++;
		elem.fadeOut(400, function () {
			$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
  	});
	}, 2000);
 });

#progress-text{
  color:red;
  font-size:30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="progress-text">
</div>

<button id="show">
Show
</button>
&#13;
&#13;
&#13;

请查看以上代码。

问题1:数组中的元素为1, 2, 3, Bye,但单击Show按钮时,数组中的第一个元素未显示,它以&开头#34; 2&#34; 2秒后。

2:我需要在到达数组中的最后一个元素后停止循环。 这意味着1, 2, 3, Bye只会显示一次。

3 个答案:

答案 0 :(得分:2)

您需要在<a id="stream1" href="#">name_1</a> 回调中增加计数器并使用clearInterval()取消定时操作

function somefunction(a) {
   document.getElementById('a').innerHTML = '<a href="http://server/'+id+'/parameters">';
}

fadout()
  elem.text(wordsArray[count++]); //To immediately show the text
  var interval = setInterval(function() {
    elem.fadeOut(400, function() {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
      count++;
      if (count == wordsArray.length) {
        clearInterval(interval)
      }
    });
  }, 2000);
$("#show").click(function() {
  var elem = $('#progress-text');
  var count = 0;
  wordsArray = ["1", "2", "3", "Bye"];
  elem.text(wordsArray[count++]);
  var interval = setInterval(function() {
    elem.fadeOut(400, function() {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
      count++;
      if (count == wordsArray.length) {
        clearInterval(interval)
      }
    });
  }, 2000);
});

答案 1 :(得分:1)

&#13;
&#13;
$("#show").click(function() {
	var elem = $('#progress-text');
	count = 0;
	wordsArray = ["1", "2", "3", "Bye"];
    elem.text(wordsArray[count++]);
	var intervalId = setInterval(function () {
		elem.fadeOut(400, function () {
			$(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
		count++;
                if (count === wordsArray.length) { 
                    clearInterval(intervalId);
                }
  	});
	}, 2000);
 });
&#13;
#progress-text{
  color:red;
  font-size:30px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="progress-text">
</div>

<button id="show">
Show
</button>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

&#13;
&#13;
$("#show").click(function() {
	var elem = $('#progress-text');
	count = 0;
	wordsArray = ["1", "2", "3", "Bye"];
	var myVar =setInterval(function (){

  if(wordsArray.length>count){
	  elem.fadeOut(400, function () {
	 	$(this).text(wordsArray[count-1]).fadeIn(400);});
    count++;
   }
   else
    clearInterval(myVar);

	}, 2000);

 });
&#13;
#progress-text{
  color:red;
  font-size:30px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="progress-text">
</div>

<button id="show">
Show
</button>
&#13;
&#13;
&#13;