【问题标题】:How to make HTML table row clickable without JQuery?如何在没有 JQuery 的情况下使 HTML 表格行可点击?
【发布时间】:2019-01-09 23:52:09
【问题描述】:

使用烧瓶,我想从表中选择一个用户,然后使用所选用户的 id 重定向页面。我的代码如下所示:

HTML:

<form action="" method="POST">
    <table>
        <tr>
            <th>Id</th>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
            {% for user in users %}
                <tr type="submit" name="action" value="{{user.user_id}}">
                    <td>{{user.user_id}}</td>
                    <td>{{user.first_name}}</td>
                    <td>{{user.last_name}}</td>
                </tr>
            {% endfor %}
    </table>
</form>

Python:

def userSelect():
if request.method == 'POST':
    return redirect(url_for('user', user=request.form['action']))
return render_template('userSelect.html', users=user.query.all())

我也尝试过使用 JQuery 来发帖,但我不确定如何使用重定向到的页面中的 id,并且在从 JQuery 发帖后我无法从烧瓶重定向:

$("table tr").on("click",function()
{
    var selected = $("td:first", this).text();
    $.post("/user", {user_id: selected}, function(){
        window.location.href = "/user";
    });
});

编辑:

假设我想在重定向到的页面上显示该 ID(类似这样):

@app.route("/user")
def user(user):
    return user

【问题讨论】:

  • 当你点击表格中的任何一行时,你想得到所选行的ID吗?
  • (表头除外)是的。当您单击该行时,我想重定向页面并知道在我重定向的页面上单击了哪个 id。

标签: python jquery html flask jinja2


【解决方案1】:

使用您的 Jquery 代码,它将生成一个 ajax 到服务器

$.post("/user", {user_id: selected}, function(){
    window.location.href = "/user";
});

所以,Flask 不能重定向,如果你编辑代码看起来像:

$.post("/user", {user_id: selected}, function(data){
    console.log(data);
});

你会看到 Flask 已经返回了重定向页面的 HTML。

最后,我认为这对您有所帮助: 烧瓶:

@app.route('/user/<user_id>')
def userHasSelected(user_id):
    ....
    // I don't know why do you need this return redirect
    return redirect(url_for('user', user=request.form['action']))

JS:

$("table tr").on("click",function()
{
    var selected = $("td:first", this).text();

    // {{url_for('user', user_id=selected)}} it will be rending from server
    window.location.href = {{url_for('user', user_id=selected)}}
    // or
    window.location.href = `/user?user_id=${selected}`;
});

【讨论】:

  • 嘿伙计,我花了一些时间,但我已经修好了。 @Thangle
猜你喜欢
  • 2021-09-24
  • 2011-10-17
  • 2022-10-07
  • 2021-10-01
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
相关资源
最近更新 更多