数组

时间:2016-08-22 14:07:02

标签: javascript jquery arrays

早上好。我使用Javascript来处理函数中的数据时遇到了问题。我是Javascript的新手,所以希望有一个简单的解释。

我的目标是按顺序显示数组中的每个项目,逐渐淡出每个项目。通过单击屏幕上的按钮调用该功能后,将启动此过程。

我尝试通过索引号迭代数组成员来完成此操作。函数不是按索引号处理和显示每个元素,而是迭代整个序列,但只显示数组的最后一个元素。但是,它通过淡入和淡出最后一个值来执行所需的次数显示。

这是我写的代码;

var tarList = [ "Sentence one.",
            "Sentence two.",
            "Sentence three.", 
            "Sentence four.",
            "Sentence five.",
            "Sentence six."];

var $button = $('button');

var index = 0;

function displayText(indexNo) {
    $("h3").text(
        tarList[indexNo]).fadeIn(700).delay(1200).fadeOut(700);
}

$button.on('click', function(){
    for (var i=0; i < tarList.length; i++) {
        console.log(i);
        displayText(i);
    }
});

CodePen http://codepen.io/cg893/pen/rLgLAP

的全部努力

我不明白为什么Javascript会在整个范围内进行迭代,并且只调用显示函数的最后一个值,尽管对显示函数的调用是在迭代范围内。我也不明白为什么淡入/淡出命令执行正确的次数但只使用数组中的最后一项。

我见过其他例子(exampleexample2),其中淡入/淡出序列是在html的列表元素上执行的。我的目标是将数组用作单独的数据源,以便可以将值作为一个组进行处理。如果唯一的方法是通过在html中包含值,有人可以提供有关如何最好地执行此操作的建议吗?谢谢。

&#13;
&#13;
var tarList = [ "Sentence one.",
                "Sentence two.",
                "Sentence three.", 
                "Sentence four.",
                "Sentence five.",
                "Sentence six."];

var $button = $('button');

var index = 0;

function displayText(indexNo) {
    $("h3").text(
        tarList[indexNo]).fadeIn(700).delay(1200).fadeOut(700);
}

$button.on('click', function(){
    for (var i=0; i < tarList.length; i++) {
        console.log(i);
        displayText(i);
    }
});
&#13;
#button_1 {
  left: 50%;
  top: 50%;
  position: absolute;
}


h3 {
  position: relative;
  margin-top: 1em;
  text-align: center;
  font-size: 2em;
  font-family: Arial;
  transition: color 1s ease-in-out;
}
&#13;
<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>





<h3 id="target_text">Start</h3>
<button id="button_1" type="submit" >Go!</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

你的for循环没有等待你的displayText()函数。它运行得很快,整个displayText()仍在处理中。

解决方案 - &gt;

$button.on('click', function(){

  function Loop () {           
    setTimeout(function () {    
    displayText(i);           
  i++;                    
  if (i < 10) {            
     Loop();           
    }                       
   }, 2600)
  }
  Loop();

  });