2012-02-08 6 views
6

jQuery 스크립트에 도움이 필요합니다. 10 초마다 새로 고치는 페이지가 있으며 피드의 새 div가 추가됩니다.20 개가 넘는 경우 오래된 div를 삭제하십시오. jQuery

내 스크립트는 20 개가 넘는 div가있는 경우 div를 계산하고 마지막 div를 제거합니다. 피드가 한 번에 1 div를 추가하면 제대로 작동합니다. 그러나 피드는 동시에 여러 div를 추가 할 수도 있습니다. 이 경우 카운트가 최대 20divs를 초과 할 수 있습니다. 이 문제는 내 스크립트가 1 div를 삭제하고 20 개를 초과하는 div를 모두 삭제하지 않는다는 것입니다. 난 항상 20 명 div가있다, 그래서 모든 추가 된 div를 제거해야

var $auto_refresh = setInterval(function() { 
    var $articleCount = $('div').length; 

    if ($articleCount > 20) { 
     $('div:last-child').remove(); 
    } 

    $autoUpdate(); 
}, 10000); // refresh every 10000 milliseconds for new items 

:

이 내 코드입니다. 누군가가 나를 도와 줄 수 있기를 바랍니다.

답변

3
var $auto_refresh = setInterval(function() { 
    var $articleCount = $('div').length; 

    while ($articleCount > 20) { 
     $('div:last-child').remove(); 
     $articleCount = $('div').length; 
    } 

    $autoUpdate(); 
}, 10000); 

공지 사항 whileif의 변화. (20)

+2

이 $의 articlecount' 실제로 업데이트하지 않기 '때문에 작동하지 않을 것'while') – Supr

+0

지금은 확실히 않습니다. –

+0

죄송합니다. [HTMLCollection being live] (http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506)의 사례라고 생각합니다. 그것의 길이를 별도의 변수로 만들었습니다 –

1

있을 때까지이는 greater than 선택기를 사용하여 마지막 하나를 삭제 유지 : http://jsfiddle.net/PLKAm/ : 당신은 인덱스 x로부터의 모든 요소를 ​​제거하기 위해 .slice(x)를 사용할 수

var $auto_refresh = setInterval(function() { 

    $('div:gt(20)').remove(); 

    $autoUpdate(); 
}, 10000); // refresh every 10000 milliseconds for new items 
+0

그는 루프 본문 내에서'$ articleCount'를 업데이트해야합니까? – xbonez

+0

': gt'는 jQuery 필터이므로 선택기의 일부로 사용하면 jQuery가 CSS 엔진을 사용하여 div를 선택하여 성능이 저하됩니다. '$ ('div'). filter (': gt (20)')'또는 이와 비슷한 ('.슬라이스()') – Joe

+0

@Joe 여기에 성능이 문제라고 생각하십니까? –

0
var $auto_refresh = setInterval(function() { 

    while ($('div').length > 20) { 
     $('div:last-child').remove(); 
    } 

    $autoUpdate(); 
}, 10000); // refresh every 10000 milliseconds for new items 
0
while ($articleCount > 20) {    
     $('div:last-child').remove(); 
     $articleCount = $('div').length; 
    } 
2

. <= 20 항목이있는 경우

$("div").slice(20).remove(); 

.slice(20)는 빈 집합을 반환하므로 코드가 자동으로 no-op입니다. 편의를 위해

0

편집 :

$('div').each(function(count){ 
    if(count >= 20){ 
     $(this).remove(); 
    } 
}); 
+0

이유가 무엇인지 모르겠다 –

+0

다음과 같이 간단히 처리 할 수 ​​있습니다. [각 함수] (http://api.jquery.com/each/)에는 두 개의 매개 변수가 있고 첫 번째 매개 변수는 인덱스이므로 count 필요가 없습니다. –

+0

@ TimBüthe 감사합니다, 수정 됨. – wanovak

6

사용 jQuery.slice은 모든 과거의 수 (20), 그리고 빈을 얻을 - 죽은 쉽게 당신은 사용할 수 있습니다 :

var $auto_refresh = setInterval(function() { 
    $('div').slice(20).remove(); 
    $autoUpdate(); 
}, 10000); // refresh every 10000 milliseconds for new items 

http://api.jquery.com/slice/

0

:gt() 셀렉터가 하나의 요소를 찾으면 급습합니다. 시

var $auto_refresh = setInterval(function() { 
    var nToDelete = $('div').length - 20; // Calculate how many there are to delete...  
    if(nToDelete > 0) $('div:gt(" + nToDelete + ")').remove(); // and delete them. 
    $autoUpdate(); 
}, 10000); 
0
var remove21 = function() { 
    if ($('div').length > 20) { 
     $('div:nth-child(21)').remove(); 
     remove21(); 
    } 
} 

var $auto_refresh = setInterval(function() { 

    remove21(); 

    $autoUpdate(); 
}, 10000); // refresh every 10000 milliseconds for new items 
관련 문제