[英]Remove all except some elements in jQuery
Consider the following page layout: 请考虑以下页面布局:
<div id="page-container" class="">
<div id="scroller">
<!-- This page should be removed -->
<div id="page_1" class="pagina"></div>
<!-- These pages should be kept -->
<div id="page_2" class="pagina"></div>
<div id="page_3" class="pagina"></div>
<!-- This is the current page -->
<div id="page_4" class="pagina"></div>
<!-- These pages should be kept -->
<div id="page_5" class="pagina"></div>
<div id="page_6" class="pagina"></div>
<!-- These pages AND everything that follows should be removed -->
<div id="page_7" class="pagina"></div>
<div id="page_8" class="pagina"></div>
</div>
</div>
I have a function loadPage(pageNr) which loads a specific page and scrolls it into view. 我有一个函数loadPage(pageNr),它加载特定页面并将其滚动到视图中。
I also have a function that load's two more pages on top, or below the current page depending on the scroll direction. 我还有一个功能,可根据滚动方向在当前页面的顶部或下方加载另外两个页面。
What I want to achieve now, is that when my loadPage() function is called, I want to keep 2 pages below and before the current page. 我现在想要实现的是,当调用loadPage()函数时,我想在当前页面的下方和之前保留2个页面。 All other pages should be removed.
所有其他页面均应删除。 This is for speed purposes as my app has 748 pages in total.
这是出于提高速度的目的,因为我的应用共有748页。
What I have tried: 我试过的
//Determine which pages on top of current page should be kept
var firstPageToKeep = (pageNr - 2);
//Delete every page on top that should not be kept in memory
for(x=0;x<firstPageToKeep;x++) {
console.log('x: '+x);
$('#page_'+x).remove();
}
//=================================
//Determine which pages below current page should be kept
var lastPageToKeep = (pageNr + 2);
//Delete every page below current page that should not be kept in memory
for(y=0;y<lastPageToKeep;y++) {
$('#page_'+y).remove();
}
This does remove every page except the current page. 这确实会删除当前页面以外的所有页面。 I believe I have set the limits of which pages should be deleted and which not.
我相信我已经设定了删除哪些页面和不删除哪些页面的限制。 Why is everything deleted except the current page?
为什么要删除除当前页面以外的所有内容?
Try this code: 试试这个代码:
$('.pagina').each(function(i, page) {
if ((i < pageNr - 3) || (i > pageNr + 1)) {
$(page).remove();
}
});
尝试这个:
$("#scroller").children().not("#id1 #id2 ...").each(function(){//Your code});
My quick guess is, that your last for-loop deletes all pages up to lastPageToKeep, keeping only the last pages. 我的快速猜测是,您的最后一个for循环将删除直到lastPageToKeep的所有页面,仅保留最后一页。 You should iterate beginning from lastPageToKeep+1 up to the maximum number of pages.
您应该从lastPageToKeep + 1开始迭代直到最大页面数。
Nevertheless I'd recommend to you the :lt
and :gt
selectors from jQuery! 尽管如此,我还是建议您使用jQuery的
:lt
和:gt
选择器!
I made a quick fiddle for you demonstrating the use: http://jsfiddle.net/d6tZ6/ 我为您演示了用法,为您进行了快速提琴制作: http : //jsfiddle.net/d6tZ6/
Note: As a side effect this will also remove the neccessity for having an ID for each page. 注意:作为副作用,这还将消除为每个页面设置ID的必要性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.