我有一个websockets应用程序,我在那里显示客户连接。我用烧瓶做前端。
当连接到新客户机时,我将其添加到python中的clients列表中。
HTML端,我有一个通过Jinja接收客户列表的表,它为每个连接的客户端创建一行。这个表每2秒用js刷新一次。
“我的客户名单”是一份字典列表:
clients = [
{ 'cp_id':'Jhon',
'last_heartbeat_from_now':datetime.utcnow()
}
...
]我的桌子是这样的:
<table id="clients">
<tr>
<th>Name</th>
<th>Last time connected </th>
<th>Health</th>
</tr>
{% for i in clients %}
<tr>
<td>{{ i['cp_id'] }}</td>
<td>{{ i['last_heartbeat_from_now'] }}</td>
<td><img src="{{ url_for('static', filename='green.png') }}" class="health"></td>
</tr>
{% endfor %}
</table>我想让每一行<tr>都是可点击的,并且重定向到一个具有人名的动态URL。例如,当我在HTML中单击Jhon时,我想要创建dynamic : localhost:5000/dashboard/Jhon。
我试着用
<tr onclick="{{ url_for('dashboard', cp_id = i['cp_id']) }}">但它什么也做不了。我试着做一个数据-href:
<tr data-href="{{ url_for('dashboard', cp_id = i['cp_id']) }}">但我不知道怎么用这个。
最后,我的路由部分的python代码是:
@app.route('/dashboard/<string:cp_id>', methods=["GET", "POST"])
def dashboard(cp_id):
return render_template('dashboard.html')发布于 2022-03-11 16:23:17
你差点就到了!
最好的方法是使用data-href
<tr data-href="{{ url_for('dashboard', cp_id = i['cp_id']) }}">您的行是动态添加的,因此您的脚本需要委托事件。这意味着onclick事件需要来自静态父事件(如果可以的话,最接近动态子事件,在本例中我使用文档)。
如果不将静态父级事件委托给动态子级,则它将无法工作。例如,就像这样:
jQuery("tr[data-href]").on("click", function () ...,这在你的html.中是行不通的
委托事件处理程序将完成任务。
然后添加您的jQuery脚本:
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery(document).on("click", "tr[data-href]", function() {
window.location.href = jQuery(this).attr('data-href');
});
});
</script>如果您想在行悬停时添加“手动”效果,只需将其添加到CSS中即可:
[data-href] { cursor: pointer }https://stackoverflow.com/questions/71440068
复制相似问题