2016-04-23 60 views
1

所以我創建了一個函數,它可以通過數組中的元素改變某個div中的文本,該函數瀏覽一個字符串數組,然後當它到達其末尾Javascript/jQuery:瀏覽一個數組並放入div中的元素

$(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); 
}); 

這是應該在每個更改單擊

<h3 id="change">this is a text</h3> 

當然還有就是元素:,它從一開始就

這裏是jQuery代碼開始按鈕

<button id="btn1">click</button> 

現在我的問題是,該功能顯示這樣的元素:

單詞2 - > WORD3 - > word4 - >的word5 - > word6 - > word6 - > word2

它不顯示第一個元素,而是顯示第六個元素兩次,你能告訴我它有什麼問題嗎?

回答

2

fadeOut函數是異步的,所以你的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 
    }); 
} 
+0

嗨,這完美地工作,但你能告訴我更多關於這個'異步'的東西,謝謝! Ps:8分鐘後你會被選爲答案:D – Yassir

+0

沒問題 - 看看這裏:http://stackoverflow.com/questions/16336367/ – smaili

1

另一種解決方案可以基於該data attributes。整個操作的管理的完成是爲了非常重要的,可以避免開始另一個循環之前,在當前一個結束:

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

 
$(function() { 
 
    $("#btn1").on('click', function(e) { 
 
    // disable button till the operation is completed 
 
    $(this).prop('disabled', 'disabled'); 
 
    
 
    // use data-currentIndex to store the local variable i 
 
    var idx = $('#change').data('currentIndex'); 
 
    if (idx === undefined) { 
 
     idx = 0; 
 
    } 
 
    $('#change').fadeOut('slow', function() { 
 
     $(this).text(array1[idx]).fadeIn('slow'); 
 
     idx = (idx <= (array1.length - 2)) ? (idx + 1) : 0; 
 
     $('#change').data('currentIndex', idx); 
 
     
 
     // enable button because the operation is now completed 
 
     $("#btn1").removeProp('disabled'); 
 
    }); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> 
 

 
<h3 id="change">this is a text</h3> 
 
<button id="btn1">click</button>

相關問題