使用 django 我有一个 HTML 页面,其中包含一个包含复选框的表格:
{% for o in obj %}
<input class='germ_ids' name='{{o.id}}'>
{% endfor %}
<script>
var elements = document.getElementsByClassName("germ_ids");
var ids = [];
for(var i=0; i<elements.length; i++) {
ids.push(elements[i].name);
}
</script>
这给了我一系列特定的“细菌 ID”。这些与我拥有的其他 django 对象相关:
相同的 .html 页面:
{% for k, v in add_state_dict.items %}
<div class='{{k.id}}_statement'>
<p>{{v}}</p>
</div>
{% endfor %}
<div class='all_germ'>
<p>{{additional_statement}}</p>
</div>
我想要实现的是在选中复选框时为每个 germ_id 提供一个声明。然而,当选中多个复选框时,它会在“all_germ”类中生成一个名为additional_statement 的concat 语句。
我已将其硬编码在 JSFiddle http://jsfiddle.net/sDsCM/1037/ 中
但是我想使用数组中的元素来执行此操作以解释不同的数组值。
最佳答案
您不应使用带有 ID 的类名,而应使用对复选框进行分类的类名。例如,我将使用 .checkbox-plus-info
。另外,使用 data
属性来查找关联的语句(除非您可以将它们呈现在一个 div 内):
{% for o in obj %}
<input class='germ_ids checkbox-plus-info' name='{{o.id}}'
data-info-tag="info-{{o.id}}">
{% endfor %}
{% for k, v in add_state_dict.items %}
<div id='{{k.id}}_statement' class="info info-{{k.obj_id}}">
<p>{{v}}</p>
</div>
{% endfor %}
在上面,k
当然需要包含对该对象的引用(其 PK/ID)。您应该在 View 中包含该信息并将其添加到上下文中。您尚未发布 View /上下文代码,但在创建模板上下文时业务逻辑应该已准备就绪,因此请尽可能做好准备。
在你的 JS 中:
$(".checkbox-plus-info").click(function() {
$(".info").hide(); // hide all
stmtElId = $(this).target.data("info-tag");
$("#" + stmtElId).show();
// check whether something has to be shown when several checkboxes are checked
// e.g. count whether all checkboxes are checked, or other logic
});
关于javascript - 使用 javascript 数组显示特定的 HTML div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030950/