我是我当前的项目,我的索引页面显示了多个种子,每个种子都有一个按钮来启动或停止种子。
我使用表单和循环创建页面,因此表单始终具有相同的名称。但是我需要知道用户单击了哪个按钮才能知道停止哪个洪流!
这里是模板:
{% block content %}
<h1>Hello, {{user}} !</h1>
{% for torrent in torrents %}
<form action="/index" method="post" name="torrent">
{{torrent.control.hidden_tag()}}
<p><a href='/torrent/{{torrent.id}}'>{{torrent.name}}</a> is {{torrent.status}} and {{torrent.progress}} % finished. <input type="submit" value="Start / Stop">
</p>
</form>
{% endfor %}
这里是视图:
@app.route('/index', methods = ['GET', 'POST'])
def index():
user = 'stephane'
torrents = client.get_torrents()
# for each torrent, we include a form which will allow start or stop
for torrent in torrents:
torrent.control = TorrentStartStop()
if torrent.control.validate_on_submit():
start_stop(torrent.id)
return render_template("index.html", title = "Home", user = user, torrents = torrents)
所以,我怎么知道用户要停止/启动哪个torrent?
[假设hidden_tag
创建一个名称为hidden
的torrent_id
输入,并指定torrent的ID,您将在request.form["torrent_id"]
中找到torrent ID:
from flask import request
....
torrent_id = request.form["torrent_id"]
[使用HTML <button type="submit">
元素,然后将value
设置为信息哈希,或设置包含信息哈希的formaction
URL(formaction
仅适用于HTML5)。
u可以在js中使用活动按钮状态,如果有人单击按钮并将其css类更改为活动按钮,然后检查哪个按钮处于活动状态并获取其信息。
这是js代码:
var btnContainer = document.getElementById("myDIV");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
这是按钮的css:
.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
.active, .btn:hover {
background-color: #666;
color: white;
}