gev*_*vra 6 javascript python django
我有一个带有以下代码的 Django 模板,它创建多个按钮并尝试通过单击(在同一个按钮上)删除/隐藏其中一个按钮:
{% for h in helicopters %}
<div class="btn-group" id="remove-heli">
<button type="button" class="btn btn-default" onclick='my_func("{{ h }}")'>
{{ h }}
</button>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
哪里helicopters是字符串列表,稍后在脚本块中我有
function my_func(h) {
document.getElementById('remove-heli').style.visibility = 'hidden';
}
Run Code Online (Sandbox Code Playgroud)
该函数运行,但正如您所料,它仅在我的 for 循环的第一个元素上运行,因为 for 循环中的所有<\div>元素都具有相同的 id。
我的问题是:有没有办法指向特定元素?或者,有没有更好的方法来打印彼此相邻的按钮?
为 div 元素设置不同的 id 怎么样?
{% for h in helicopters %}
<div class="btn-group" id="remove-heli-{{ h }}">
<button type="button" class="btn btn-default" onclick='my_func("{{ h }}")'>
{{ h }}
</button>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用 id 访问特定的 div 元素。
function my_func(h) {
document.getElementById('remove-heli-' + h).style.visibility = 'hidden';
}
Run Code Online (Sandbox Code Playgroud)
笔记
对多个元素使用相同的 ID 不是一个好主意。使用唯一标识。
更新
或者,您可以使用forloop.counter:
{% for h in helicopters %}
<div class="btn-group" id="remove-heli-{{ forloop.counter }}">
<button type="button" class="btn btn-default" onclick='my_func("{{ h }}")'>
{{ h }}
</button>
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2532 次 |
| 最近记录: |