我的目标是在JSON文件中有一个引号列表并通过它们进行旋转。一切看起来都很好,javascript正在运行适当的次数,实际上像预期的那样淡入淡出,但不知怎的,它只显示数组的最后一个键。
简单的html:
<div class="testimonial__content"></div>
使用Javascript:
var testimonials = [{
"quote" : "Always remember that you are absolutely unique. Just like everyone else.",
"image": "http://placekitten.com/g/50/50"
},
{
"quote" : "People who think they know everything are a great annoyance to those of us who do.",
"image": "http://placekitten.com/g/50/50"
}
];
var currentQuote = $(".testimonial__content");
for (var key in testimonials) {
var myHtml = testimonials[key].quote;
changeHtml (myHtml);
}
function changeHtml(myhtml){
currentQuote
.fadeIn(2000)
.delay(2000)
.text(myhtml)
.fadeOut(2000);
}
小提琴:http://jsfiddle.net/janL3r6v/
我想我可以尝试不同的方法来使其发挥作用,但我不理解为什么它运行了适当的次数但它只获得了最后一个阵列。此外,调试myHtml
会显示所有引号。
答案 0 :(得分:2)
您必须等到上一个动画完成后再开始下一个动画。您可以通过在fadeOut
:
var testimonials = [{
"quote": "Always remember that you are absolutely unique. Just like everyone else.",
"image": "http://placekitten.com/g/50/50"
}, {
"quote": "People who think they know everything are a great annoyance to those of us who do.",
"image": "http://placekitten.com/g/50/50"
}];
var currentQuote = $(".testimonial__content");
var quoteIndex = 0;
function changeHtml() {
var myHtml = testimonials[quoteIndex].quote;
quoteIndex = (quoteIndex + 1) % testimonials.length;
currentQuote
.fadeIn(2000)
.delay(2000)
.text(myHtml)
.fadeOut(2000, changeHtml);
}
$(document).ready(function() {
changeHtml(); // Start the cycle
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testimonial__content"></div>