我有一個 websockets 應用程式,我在其中顯示連接的客戶端。我使用燒瓶作為前端。
連接新客戶端后,我將其添加到clientspython 的串列中。
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 時,我想創建動態 url: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')
uj5u.com熱心網友回復:
你快到了!
最好的方法是使用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://www.uj5u.com/shujuku/443958.html
標籤:javascript Python html 烧瓶 神社2
上一篇:通過Flask發送n行大檔案?
