python烧瓶应用中的下拉选项过滤(带JavaScript)

发布于 2025-02-12 03:48:57 字数 2325 浏览 0 评论 0 原文

我正在尝试使用下拉词来过滤表中的结果。我试图使其与AddEventListener('click')一起使用,但是我一直坚持如何使其功能正常。我认为我很近,但缺少一些东西。

谁能提供帮助提供一个解决方案,以便当在下拉列表中单击国家价值时,它会过滤到表中所有具有相应国家价值的人?这将需要工作,以便将使用多个列上的多个下拉列表。

python

app = Flask(__name__)
test_data = [['jack', 23, 'china', 'https://www.google.com'],
             ['jill', 22, 'canada', 'https://www.cnn.com'],
             ['john', 24, 'canada', 'https://www.cnn.com'],
             ['jane', 30, 'australia', 'https://www.bbc.com']]

test_df = pd.DataFrame(test_data, columns=['name', 'age', 'country', 'link'])
test_df = test_df.to_dict(orient='index')
@app.route("/hello")
def index():
    return render_template("index.html", test_df=test_df)

html :在index.html

<div class="container">
    <label for="country">Countries</label>
    <form class="form">
        <div class="form__group">
            <select id="country" name="country" data-dropdown>
                <option value="">Please select a country</option>
                <option value="australia">Australia</option>
                <option value="canada">Canada</option>
                <option value="china">China</option>
            </select>
        </div>
    </form>
</div>

<table class="table">
    <tbody id="myTable">
    </tbody>
</table>

javascript 中:在脚本标签中的index.html中

var mydata = JSON.parse('{{ test_df|tojson }}');
var countrySelector = document.getElementById('country');
// but what next?

buildTable(mydata)
function buildTable(data) {
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var key in data) {
        var row = `<tr>
                    <td>${data[key].name}</td>
                    <td>${data[key].age}</td>
                    <td><a href="${data[key].link}" target='_blank'>${data[key].country}</a></td>
               </tr>`
        table.innerHTML += row
    }
}

I'm trying to use drop-downs to filter results in a table. I've tried to make it work with addEventListener('click'), but I'm stuck on how to make it fully functional. I think I'm very close but missing something.

Could anyone help to provide a solution such that when the country values are clicked in the drop-down, it filters for all of those with corresponding country values in the table? This will need to work such that multiple drop-downs on multiple columns would be used.

enter image description here

Python

app = Flask(__name__)
test_data = [['jack', 23, 'china', 'https://www.google.com'],
             ['jill', 22, 'canada', 'https://www.cnn.com'],
             ['john', 24, 'canada', 'https://www.cnn.com'],
             ['jane', 30, 'australia', 'https://www.bbc.com']]

test_df = pd.DataFrame(test_data, columns=['name', 'age', 'country', 'link'])
test_df = test_df.to_dict(orient='index')
@app.route("/hello")
def index():
    return render_template("index.html", test_df=test_df)

HTML: in an index.html

<div class="container">
    <label for="country">Countries</label>
    <form class="form">
        <div class="form__group">
            <select id="country" name="country" data-dropdown>
                <option value="">Please select a country</option>
                <option value="australia">Australia</option>
                <option value="canada">Canada</option>
                <option value="china">China</option>
            </select>
        </div>
    </form>
</div>

<table class="table">
    <tbody id="myTable">
    </tbody>
</table>

JavaScript: within the index.html in script tags

var mydata = JSON.parse('{{ test_df|tojson }}');
var countrySelector = document.getElementById('country');
// but what next?

buildTable(mydata)
function buildTable(data) {
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var key in data) {
        var row = `<tr>
                    <td>${data[key].name}</td>
                    <td>${data[key].age}</td>
                    <td><a href="${data[key].link}" target='_blank'>${data[key].country}</a></td>
               </tr>`
        table.innerHTML += row
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

殊姿 2025-02-19 03:48:57

使用select元素的
以下示例向您展示了如何按国家过滤行。为了使在JavaScript中过滤行更容易,它们不是作为DICT传递的,而是使用 df.values.tolist()作为列表。

from flask import (
    Flask, 
    render_template
)
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    test_df = pd.DataFrame(
        [
            ['jack', 23, 'china', 'https://www.google.com'],
            ['jill', 22, 'canada', 'https://www.cnn.com'],
            ['john', 24, 'canada', 'https://www.cnn.com'],
            ['jane', 30, 'australia', 'https://www.bbc.com']
        ],
        columns=['name', 'age', 'country', 'link']
    )
    return render_template('index.html', test_df=test_df.values.tolist())
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <div class="container">
      <label for="country">Countries</label>
      <form class="form">
        <div class="form__group">
          <select id="country" name="country" data-dropdown>
            <option value>Please select a country</option>
            <option value="australia">Australia</option>
            <option value="canada">Canada</option>
            <option value="china">China</option>
          </select>
        </div>
      </form>
    </div>

    <table class="table">
      <tbody id="myTable">
      </tbody>
    </table>

    <script type="text/javascript">

      function buildTable(data) {
          const table = document.getElementById('myTable')
          table.innerHTML = data.map(row => {
            let [name, age, country, link] = row;
            return `<tr>
                <td>${name}</td>
                <td>${age}</td>
                <td><a href="${link}" target='_blank'>${country}</a></td>
              </tr>`;
          }).join('');
      }

      const data = {{ test_df|tojson }};
      const countrySelector = document.getElementById('country');
      countrySelector.addEventListener('change', evt => {
        const value = evt.target.value;
        if (value) {
          buildTable(data.filter(row => {
            let [name, age, country, link] = row;
            return country === value
          }));
        } else {
          buildTable(data);
        }
      });

      buildTable(data)

    </script>

  </body>
</html>

Use the select element's change event to monitor user changes in the selection.
The following example shows you how to filter the rows by country. To make it easier to filter the rows in JavaScript, they are not passed as a dict but as a list using df.values.tolist().

from flask import (
    Flask, 
    render_template
)
import pandas as pd

app = Flask(__name__)

@app.route('/')
def index():
    test_df = pd.DataFrame(
        [
            ['jack', 23, 'china', 'https://www.google.com'],
            ['jill', 22, 'canada', 'https://www.cnn.com'],
            ['john', 24, 'canada', 'https://www.cnn.com'],
            ['jane', 30, 'australia', 'https://www.bbc.com']
        ],
        columns=['name', 'age', 'country', 'link']
    )
    return render_template('index.html', test_df=test_df.values.tolist())
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index</title>
  </head>
  <body>
    <div class="container">
      <label for="country">Countries</label>
      <form class="form">
        <div class="form__group">
          <select id="country" name="country" data-dropdown>
            <option value>Please select a country</option>
            <option value="australia">Australia</option>
            <option value="canada">Canada</option>
            <option value="china">China</option>
          </select>
        </div>
      </form>
    </div>

    <table class="table">
      <tbody id="myTable">
      </tbody>
    </table>

    <script type="text/javascript">

      function buildTable(data) {
          const table = document.getElementById('myTable')
          table.innerHTML = data.map(row => {
            let [name, age, country, link] = row;
            return `<tr>
                <td>${name}</td>
                <td>${age}</td>
                <td><a href="${link}" target='_blank'>${country}</a></td>
              </tr>`;
          }).join('');
      }

      const data = {{ test_df|tojson }};
      const countrySelector = document.getElementById('country');
      countrySelector.addEventListener('change', evt => {
        const value = evt.target.value;
        if (value) {
          buildTable(data.filter(row => {
            let [name, age, country, link] = row;
            return country === value
          }));
        } else {
          buildTable(data);
        }
      });

      buildTable(data)

    </script>

  </body>
</html>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文