使用javascript数组显示特定的HTML div

时间:2017-07-11 09:45:12

标签: javascript jquery html django checkbox

使用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>

这给了我一系列具体的生殖细胞&#39;。这些与我拥有的其他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; all_germ&#39;中创建一个名为additional_statement的concat语句。类。

我在JSFiddle http://jsfiddle.net/sDsCM/1037/

中对其进行了硬编码

但是我想使用数组中的元素来计算不同的数组值。

1 个答案:

答案 0 :(得分:0)

您不应该使用带有ID的类名,而应使用对您的复选框进行分类的类名。例如,我将使用.checkbox-plus-info。此外,使用data属性查找关联的语句(除非您可以在一个div中呈现它们):

{% for o in obj %}
    <input class='germ_ids' name='{{o.id}}' class="checkbox-plus-info"
        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)。您应该在视图中包含该信息并将其添加到上下文中。您还没有发布您的视图/上下文代码,但在创建模板上下文时,业务逻辑应该已经准备就绪,因此请尽可能多地做好准备。

在你的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
});