2016-04-23 18 views
1

配列から要素によって特定のdiv内のテキストを変更する関数を作成しました。この関数は文字列の配列をブラウズし、 、それはここに始まりJavascript/JQuery:配列をブラウズして要素を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); 
}); 

これは、各

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

をクリックして、もちろんありに変更する必要があります要素であり、ボタン

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

は今私の問題は、関数は、このような要素を示し、ということである:

ワード2 - >ワード3 - > WORD4 - > word5 - > word6 - > word6 - > word2

最初の要素が表示されず、6番目の要素が2回表示されます。何が間違っているのか教えてください。

答えて

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に基づくことができます。全体の運用管理の完了は、現在の1が終了する前に別のサイクルを開始することを避けるために非常に重要です:

//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>

関連する問題