我想把类型的编号设置为select标签的id

2024-06-26 13:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把类型的编号设置为select标签的id。 我理想的浏览器html是

 <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;">
      <option value="0">---</option>
      <option value="1">a</option>
      <option value="2">b</option>
    </select>
    <select name="type" id="type1">
      <option value="1">a1</option>
      <option value="2">a2</option>
    </select>
    <select name="type" id="type2">
      <option value="5">b1</option>
      <option value="6">b2</option>
    </select>

现在browse中的实际html是

   <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;">
            <option>---</option>  
            <option>a</option> 
            <option>b</option>  
    </select>

    <select name="type" id="type">
        <option value="0">---</option>
        <option value="1">a1</option>   
        <option value="2">a2</option>   
    </select>

    <select name="type" id="type">
        <option value="5">---</option>
        <option value="6">b1</option>
        <option value="7">b2</option>  
    </select>

id=“type”of没有每个数字,但我不知道如何使用Django的模板添加这些数字。 我用index.html写的

<form method="post" action="">
    <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;">
    {% for i in json_data.items.values %}
            <option>{{ i }}</option>
    {% endfor %}
    </select>


    {% for key, values in preprocessed %}
    <select name="type" id=type>
    {% for counter, value in values %}
        <option value="{{ counter }}">{{ value }}</option>
    {% endfor %}
    </select>
    {% endfor %}
    </form>

我该写什么?我该怎么修


Tags: nameiddatavaluestylehtmltypewidth
2条回答
<form method="post" action="">
    <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;">
    {% for i in json_data.items.values %}
            <option>{{ i }}</option>
    {% endfor %}
    </select>


    {% for key, values in preprocessed %}
        <select name="type" id=type-{{ key }}>
        {% forvalue in values %}
            <option value="{{ forloop.counter0 }}">{{ value }}</option>
        {% endfor %}
        </select>
    {% endfor %}
</form>

最好在类型中使用键,以便以后可以轻松地引用它。也不需要单独的计数器变量。Django模板标记为此提供了forloop.counter。forloop.counter以0开始计数器索引,forloop.counter以1开始计数器索引。希望这能消除您的疑虑

参考-https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#for

使用forloop.counter而不是计数器:

{% for key, values in preprocessed %}
<select name="type" id=type{{forloop.counter}}>
  {% for counter, value in values %}
  <option value="{{ forloop.counter }}">{{ value }}</option>
  {% endfor %}
</select>
{% endfor %}

相关问题 更多 >