javascript - 使用 JavaScript 对 HTML 中的 Python/Flask 动态呈现的表进行排序

标签 javascript python-3.x html flask jinja2

这是我第一次构建网络应用程序,我想从头开始学习基础知识。所以我有一个 Python 脚本,我想用它在终端上打印数据表来练习,并决定使用 Flask、HTML、CSS、JS 在网页上显示该表。到目前为止,我已经开始工作了。

现在,我想通过单击表格标题对该表格进行排序。

这是我的代码的整体分解以及到目前为止我所做的:

Python 脚本

from flask import Flask, render_template, request, url_for
app = Flask(__name__)

def get_table():
...
return dict    //returns list of dictionaries, for example... 
               //dict = [{'name':'Joe','age':'25'},
               //        {'name':'Mike','age':'20'}, 
               //        {'name':'Chris','age':'29'}] 



@app.route("/")
def home():
    return render_template('home.html')


@app.route("/table", methods = ['POST','GET'])
def table():
    if request.method == 'GET':       //When button pressed on homepage
        dict_table = get_table()      //return list of dictionaries of names and ages
        return render_template('table.html', dict_table=dict_table)

if __name__ == '__main__':
    app.run(debug=True)

HTML 文件 table.html

<!DOCTYPE html>
<html>
<head>
    <title>Display Table</title>
    <script type="text/javascript" src="/scripts/app.js"></script>
</head>
<body>
        <table id="table">
        {% if dict_table %}
        <tr>
            {% for key in dict_table[0] %}
                <th onclick="sortTable(1)" style="cursor:crosshair">{{ key }}</th>
            {% endfor %}
        </tr>
        {% endif %}

        {% for dict in dict_table %}
        <tr>
            {% for value in dict.values() %}
                <td>{{ value }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </table>
</body>
</html>

所以表格在我的网络浏览器上正确显示。我在我的 app.js 脚本中使用了他们在 W3 学校网站上教授的排序功能。

app.js

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc"; 
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      //Each time a switch is done, increase this count by 1:
      switchcount ++;      
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}

这是我从 https://www.w3schools.com/howto/howto_js_sort_table.asp 得到的例子

这些是我目前遇到的问题

  1. 当我调用该函数 sortTable 时,在示例中,它们为 sortTable(n) 提供了参数 0 和 1,因为它们的表不像我的那样动态呈现。如果我尝试使用该函数对我的表进行排序,我该如何处理这种情况,因为我的表是动态创建的?我指的是我的 HTML 文件中的 行。我找不到他们教如何处理这种情况的资源,我想学习。
  2. 如果我给它一个参数 1,当我点击我的表格标题时,没有任何反应。有人可以指导我找出错误所在以及如何解决吗?我在想这是因为表是在创建标题后在循环中创建的,所以它没有什么可以迭代的。

如果有人能指导我解决这个问题,我会很高兴。我也愿意听听是否有更好的方法让我做到这一点,只要它不是过于复杂并且涉及安装外部应用程序就像我见过的类似问题的一些解决方案(因为我只是一个初学者,正在努力学习)。谢谢!

最佳答案

sortTable函数中的

参数n为行号。当您呈现表的标题时,您总是传递 1。要修复它,您可以尝试

{% for key in dict_table[0] %}
  <th onclick="sortTable({{ loop.index0 }})" style="cursor:crosshair">{{ key }}</th>
{% endfor %}

这应该可以解决问题。

欲了解更多信息,请访问此 jinja tricks page和完整的 jinja documentation .

UPD 还有一个列表 control structures .

关于javascript - 使用 JavaScript 对 HTML 中的 Python/Flask 动态呈现的表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701959/

相关文章:

javascript - 什么是低级 Javascript?

javascript - Angularjs 指令更改 ng-model

javascript - D3 "Sunburst"中心路径大小

python - Matplotlib path.contains_points 对某些边上的点返回 false 而对其他边不返回

javascript - 如何将javascript应用于模拟浏览器的html

javascript - 滚动时加载内容

python-3.x - Pandas groupby 然后为每个组添加新行

python - Django Rest框架ApiView返回可执行文件

html - css - div 在父字段集之外溢出

javascript - 单击 div 时在弹出窗口中打开 YouTube 链接