我在 Django 模板中动态获取复选框,如下所示:
<td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
<td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
有一个像这样的取消共享按钮:
<button>Unshare</button>
我想仅在用户单击复选框时显示取消共享
按钮。
最佳答案
首先向您的模板添加更多 id,以便您可以识别元素。
<table id="choices">
{% for choice in choices %}
<td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
<td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
{% endfor %}
</table>
然后给按钮一个id和一个内联样式 -
<button id="unshare_button" style="display: none;">Unshare</button>
然后使用以下 JavaScript(一旦出现任何一个,就会显示该按钮) 单击复选框 - 如果未选中它们,则不会隐藏按钮)。
var choices_table = document.getElementByID('choices');
var checkboxes = choices_table.getElementsByTagName('input');
var unshare_button = document.getElementByID('unshare_button');
for (var i = checkboxes.length; i > 0; i--) {
checkboxes[i].addEventListener('click', function() {
unshare_button.style.display = 'inline';
}
}
恐怕我还没有检查过这段代码,但它应该可以给你一个想法。
关于javascript - 仅当通过复选框选择文件时才在 Django 模板中显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14621325/