【问题标题】:Use a javascript array to display specific HTML divs使用 javascript 数组显示特定的 HTML div
【发布时间】:2017-07-11 09:45:11
【问题描述】:

使用 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”类中称为adeauft_statement的concat语句。

我已将其硬编码在 JSFiddle http://jsfiddle.net/sDsCM/1037/

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

【问题讨论】:

    标签: javascript jquery html django checkbox


    【解决方案1】:

    您不应使用带有 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)。您应该在视图中拥有该信息并将其添加到上下文中。您尚未发布您的视图/上下文代码,但在您创建模板上下文时,业务逻辑应该已经准备就绪,因此请尽可能多地准备。

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

    【讨论】:

    • 您好,感谢您的回复。我已经在我的代码中尝试过这个,但它不起作用 - (".info").hide();没有作为一个开始。我也在 jsfiddle 中尝试过这个 - jsfiddle.net/pglove/MXNbK/17 并且遇到了同样的问题
    • 我不认为点击处理程序被调用。我尝试使用警报()。你确定 jQuery 在里面设置正确吗?
    • 我不明白你的意思
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多