Javascript/JQuery:浏览数组并将元素放入div中

Javascript/JQuery:浏览数组并将元素放入div中,javascript,jquery,html,css,arrays,Javascript,Jquery,Html,Css,Arrays,所以我做了一个函数,它通过数组中的元素来改变某个div中的文本,这个函数浏览一个字符串数组,当它到达它的末尾时,它从一开始就开始了 以下是JQuery代码: $(document).ready(function() { //This is the array with multiple elements var array1=["word1" , "word2" , "word3" , "word4" , "word5" , "word6" ]; var i=0; //This is my

所以我做了一个函数,它通过数组中的元素来改变某个div中的文本,这个函数浏览一个字符串数组,当它到达它的末尾时,它从一开始就开始了

以下是JQuery代码:

$(document).ready(function() {

//This is the array with multiple elements
var array1=["word1" , "word2" , "word3" , "word4" , "word5" , "word6" ];
var i=0;

//This is my function
function f1()
{
    if(i<6)
    {
        $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        });
        i++;
    }
    else
    {
        i=0;
        $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        });
        i++;
    }

}

$("#btn1").click(f1);
});
$(文档).ready(函数(){
//这是包含多个元素的数组
var array1=[“word1”、“word2”、“word3”、“word4”、“word5”、“word6”];
var i=0;
//这是我的职责
函数f1()
{
如果(i)字3-->字4-->字5-->字6-->字6-->字2


它不显示第一个元素,而是两次显示第六个元素,你能告诉我它有什么问题吗?

淡出功能是异步的,所以你的
i++
发生在函数实际完成之前。你需要做的是在动画完成后将
i++
移动到

请看这里:

if(i<6)
{
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}
else
{
    i=0;
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}

if(i另一个解决方案可以基于。完成整个操作的管理非常重要,以避免在当前循环完成之前开始另一个循环:

//这是包含多个元素的数组
var array1=[“word1”、“word2”、“word3”、“word4”、“word5”、“word6”];
$(函数(){
$(“#btn1”)。在('click',函数(e){
//禁用按钮,直到操作完成
$(this.prop('disabled','disabled');
//使用data currentIndex存储局部变量i
var idx=$('#change')。数据('currentIndex');
if(idx==未定义){
idx=0;
}
$(“#更改”).fadeOut('slow',function(){
$(this).text(array1[idx]).fadeIn('slow');

idx=(idx嗨,这很好用,但是你能告诉我更多关于“异步”的事情吗,谢谢!Ps:8分钟后你会被选为答案:D
<button id="btn1">click</button>
if(i<6)
{
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}
else
{
    i=0;
    $('#change').fadeOut('slow', function() {
        $(this).text(array1[i]).fadeIn('slow');
        i++; // <-- move here
    });
}