如何将循环div的id获取到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);
}

如何在javascript中获取{{loop.index}}的值作为索引?

您可以使用事件目标属性:

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;">

最新更新