2022-06-09 pywebio table sort 表格排序

官方都没找到如何给默认的表格排序。。。结合jquery的例子改了下,默认的put_table 没有<thead>,所以需要单独分离出来head 和 rows,然后在拼接回去。

# -*- encoding: utf-8 -*-"

from pywebio.input import *
from pywebio.output import *
from pywebio import config
from flask import Flask

app = Flask(__name__)
app.config.from_object('flask_config')

js_code = '''
    $(document).on('click','th',function(){
        var table = $(this).parents('table').eq(0);
        var head = table.find('tr:eq(0)').toArray()
        var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
        this.asc = !this.asc;
        if (!this.asc){rows = rows.reverse();}
        table.children('tbody').empty().html(head).append(rows);
    });
    function comparer(index) {
        return function(a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index);
            return $.isNumeric(valA) && $.isNumeric(valB) ?
                valA - valB : valA.localeCompare(valB);
        };
    }
    function getCellValue(row, index){
        return $(row).children('td').eq(index).text();
    }
'''

@config(js_code=js_code)
def test():
    put_table([
        ['Commodity', 'Price', 'Count'],
        ['Apple', '5.5', 4],
        ['Banana', '7', 2],
        ['orange', '3', 5]
    ])

if __name__ == '__main__':
    # `task_func` is PyWebIO task function
    app.add_url_rule('/', 'test', webio_view_local(test), methods=['GET', 'POST'])
    app.run(host='0.0.0.0', port=5000)

参考文档:
https://www.hujiangtao.cn/2017/03/jquery-table-order/#%E7%9B%AE%E5%BD%95
https://pywebio.readthedocs.io/en/latest/guide.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 10点半睡,6点半起,2+6.5=8.5小时有核心技术的人,才能活到最后。 iOS 阅读整理在sourcetree...
    士梦阅读 3,092评论 0 18
  • 有一起学Python的小伙伴别忘记加入我们的Python学习交流群群:367203382 一、算法设计[https...
    ztloo阅读 939评论 0 7
  • Bookmarks 书签栏 入职 华为新员工小百科(刷新时间202003023) - 人才供应知多少 - 3MS知...
    Btrace阅读 1,456评论 0 0
  • google搜索 https://www.osjapan.net https://ipv6.google-api....
    zwb_jianshu阅读 917评论 0 0
  • 免费计算机书籍汇总。 没有注明语种的,都为英语资源。 目录 一、Web 开发[#%E4%B8%80web-%E5%...
    天涯学馆阅读 1,103评论 1 2