首页 > 解决方案 > JS 访问 forloop 中的每一个元素

问题描述

我希望for循环中的一个按钮可以独立运行相同的功能,以便在单击时单击隐藏,但单击后没有响应。

html for循环:

         {% for order_item in orders %}
          <a class="btn btn-warning" >Upload File</a>
          <input type="file" id="img-file{{ forloop.counter }}" hidden="hidden"/>
          <button type="button" onclick="function upload_img({{ forloop.counter }}){}">Upload</button>
        {% endfor %}

js:

<script>
function upload_img(x) {
    const realFileBtn = document.getElementById('img-file'+x);

    realFileBtn.click()

}
</script>

标签: javascriptdjangofor-loop

解决方案


您需要在内部调用函数onclick而不是定义。

onclick="upload_img({{ forloop.counter }})"

推荐阅读