要实现隐藏数据页码,只有在点击时才显示全部页码,你可以修改模板文件和视图函数。以下是修改后的代码示例:
模板文件 “myadmin/order/index.html”:
<script>
function togglePages() {
var pagination = document.querySelector('.pagination');
if (pagination.classList.contains('show-all-pages')) {
pagination.classList.remove('show-all-pages');
} else {
pagination.classList.add('show-all-pages');
}
}
</script>
<div class="pagination">
{% for page_num in plist %}
{% if page_num == pIndex or page_num|add:-1 == pIndex or page_num|add:1 == pIndex %}
<a href="?pIndex={{ page_num }}">{{ page_num }}</a>
{% elif forloop.first or forloop.last %}
<a href="?pIndex={{ page_num }}">{{ page_num }}</a>
{% else %}
<!-- 隐藏的页码 -->
<span class="hidden-page">{{ page_num }}</span>
{% endif %}
{% endfor %}
<button onclick="togglePages()">更多页码</button>
</div>
<style>
.hidden-page { display: none; }
.pagination.show-all-pages .hidden-page { display: inline-block; }
</style>
<!-- 其他展示订单列表的内容 -->
视图函数:
def index(request, pIndex=1):
'''浏览信息'''
nmod = Orders.objects
nlist = nmod.filter(status__lt=9)
mywhere = []
# 获取并判断搜索条件
kw = request.GET.get("keyword", None)
if kw:
nlist = nlist.filter(Q(username__contains=kw) | Q(nickname__contains=kw))
mywhere.append('keyword=' + kw)
# 获取、判断并封装状态status搜索条件
status = request.GET.get('status', '')
if status != '':
nlist = nlist.filter(status=status)
mywhere.append("status=" + status)
nlist = nlist.order_by("id") # 对id排序
# 执行分页处理
pIndex = int(pIndex)
page = Paginator(nlist, 10) # 以每页10条数据分页
maxpages = page.num_pages # 获取最大页数
# 判断当前页是否越界
if pIndex > maxpages:
pIndex = maxpages
if pIndex < 1:
pIndex = 1
list2 = page.page(pIndex) # 获取当前页数据
plist = page.page_range # 获取页码列表信息
context = {"orderlist": list2, 'plist': plist, 'pIndex': pIndex, 'maxpages': maxpages, 'mywhere': mywhere}
return render(request, "myadmin/order/index.html", context)
在这个示例中,我添加了 JavaScript 函数 togglePages() 来切换是否显示全部页码。在模板中隐藏的页码使用 <span> 元素包裹,并应用了 .hidden-page 类来进行样式控制。
点击 “更多页码” 按钮时,会调用 togglePages() 函数来切换 .pagination 元素上是否存在 .show-all-pages 类。当存在该类时,隐藏的页码将显示出来。再次点击按钮切换时,隐藏的页码将重新隐藏。
这样就实现了初步的数据页码隐藏和点击展示全部页码的效果。你可以根据需要对 JavaScript 和 CSS 样式进行调整。
内容由零声教学AI助手提供,问题来源于学员提问




