簡體   English   中英

如何將循環 div 的 id 獲取到 javascript

[英]how to get id of looped div into javascript

這是我的 HTML 表格的 Div:

<div class="form-image">
   <table>
      <tr>
         {% for count in 1..10 %} 
         <td id="form-image">
            {{loop.index}}
            <label for="file"> <img src="/OLX/Views/images/photo.png" id="{{loop.index}}" ></label>
            <input type="file"  accept="image/*" name="image" id="file"  onchange="change({{loop.index}},event)" style="display: none;">
            <br>
            <input type="radio" name="cover-image" value="">
         </td>
         {% if count == 5 %}
      </tr>
      <tr>
         {% endif %}
         {% endfor %}
      </tr>
   </table>
</div>

這是我的 Javascript 以顯示上傳的圖像:

function change (index,event) {
        alert(index);
        var image = document.getElementById(''+index+'');
        alert(image);
        image.src = URL.createObjectURL(event.target.files[0]);
        index = index+1;
        alert(index);
}

如何將 {{loop.index}} 的值作為 javascript 中的索引?

您可以使用事件目標屬性:

 change = (e) => { console.log(e.target.attributes.key.value) }
 <input id="someId" key="yourIndex" onchange="change(event)">

在你的情況下:

<input type="file"  accept="image/*" name="image" id="file" key="{{loop.index}}"
 onchange="change(event)" style="display: none;">

 function change (event) {
     var index = event.target.attributes.key.value
 }

編輯:

刪除 id 的:

<td id="form-image">
<input type="file"  accept="image/*" name="image" id="file"  onchange="change({{loop.index}},event)" style="display: none;">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM