【发布时间】:2016-08-22 14:07:01
【问题描述】:
早上好。我在使用 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 会遍历整个范围并且只使用最后一个值调用显示函数,尽管对显示函数的调用在迭代范围内。我也不明白为什么淡入/淡出命令执行正确的次数,但只使用数组中的最后一项。
我见过其他示例(example、example2),其中淡入/淡出序列是在 html 中的列表元素上执行的。我的目标是将数组用作单独的数据源,以便可以将值作为一个组进行处理。如果做到这一点的唯一方法是在 html 中包含值,有人可以就如何最好地做到这一点提供建议吗?谢谢你。
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);
}
});
#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;
}
<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>
【问题讨论】:
标签: javascript jquery arrays