2017-01-11 1 views
1

내 사이트 상단에 알림이라는 div가 있습니다. 텍스트 배열을 순환하여 각 값을 30 초마다 그 div 내에서 차례대로 표시하려고합니다.왜이 코드 (jquery each.)가 1st 후에 멈 춥니 까?

내가 작성한 아래 코드는 작동하지 않으며 여러 번 시도했지만 그 중 몇 가지를 시도했지만 아무 것도 작동하지 않았습니다.

var my_array = ["first text", "second text", "third text"]; 

jQuery.each(my_array, function(index, value) { 
    jQuery('.notifications').replaceWith(value).delay(500); 
}); 
+1

.delay '()'애니메이션 일시. '.replaceWith()'는 애니메이션이 아닙니다. – JJJ

+0

게시물을 참조하는 각() 루프를 통해 배열을 사용하지 않습니다 ... 그래서 내 질문에 대답 할 수있는 유효한 참조. – Ryan

+0

전혀 연구 했습니까? [lots] (http://stackoverflow.com/questions/12450383/how-do-you-make-text-change-every-second)와 [lots] (http://stackoverflow.com/questions/32445323)가 있습니다./jquery-replace-text-each-two-second-with-array에서) 필요한 항목을 수행하는 것에 대한 질문 –

답변

2

delay() 방법을 사용하면 replaceWith() 방법을 사용할 수 있도록 애니메이션 대기열에 지연을 제공하기 위해 사용하고 있습니다. 둘째로 replaceWith()은 전체 요소를 DOM 트리의 새 요소로 대체하므로 두 번째 반복에서는 요소가 이미 대체되었으므로 jQuery('.notifications')은 아무 것도 선택하지 않습니다.

setInterval 메서드를 사용하려면 전체 요소를 바꾸는 대신 text() 메서드를 사용하여 요소의 내용을 업데이트하면됩니다.

var my_array = ["first text", "second text", "third text"]; 
 

 
// variable for counting 
 
var i = 0; 
 

 
// initialize interval and cache the return id 
 
// to clear the interval later 
 
var inter = setInterval(change, 500); 
 
// call the function to execute initially 
 
change(); 
 

 
function change() { 
 
    // update the content 
 
    jQuery('.notifications').text(my_array[i++]); 
 
    // check count reache the length of array 
 
    if (i == my_array.length) 
 
    // if reached length of array then clear the interval 
 
    clearInterval(inter); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<span class="notifications"></span>

관련 문제