简体   繁体   English

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

[英]Use a javascript array to display specific HTML divs

Using django I have a HTML page with a table containing checkboxes:使用 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>

This has given me an array of specific 'germ ids'.这给了我一系列特定的“细菌 ID”。 These relate to other django objects I have:这些与我拥有的其他 django 对象有关:

the same.html page: same.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>

What I want to achieve is a statement for each germ_id when their checkbox is checked.我想要实现的是每个 germ_id 的复选框被选中时的声明。 However when more than one boxes are checked, it makes a concat statement called additional_statement in the 'all_germ' class.但是,当检查了多个框时,它会在“ all_germ”类中制作一个称为frome_statement的contat语句。

I have hard coded it in in a JSFiddle http://jsfiddle.net/sDsCM/1037/我已经在 JSFiddle http://jsfiddle.net/sDsCM/1037/中对其进行了硬编码

However I want to use the elements in the array to do this to account for different array values.但是我想使用数组中的元素来执行此操作以说明不同的数组值。

You should not be using class names with IDs but instead use class names that categorize your checkboxes.您不应使用带有 ID 的类名,而应使用对复选框进行分类的类名。 As example I'll be using .checkbox-plus-info .例如,我将使用.checkbox-plus-info Also, use a data attribute to find the associated statement (unless you can render them inside one div):此外,使用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 %}

In the above, k of course needs to contain a reference to the object (its PK/ID).在上面, k当然需要包含对对象的引用(它的 PK/ID)。 You should have that information in your view and add it to the context.您应该在视图中包含该信息并将其添加到上下文中。 You haven't posted your view/context code but the business logic should mostly be ready while you create the template context, so prepare as much as you can there.您还没有发布您的视图/上下文代码,但是在您创建模板上下文时业务逻辑应该已经准备就绪,所以尽可能多地准备。

In your JS:在你的 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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM