In the given code I am trying to add a dynamic ID to a div inside the foreach
loop on the basis of var i
.
However, I can't find the correct syntax, and the same issue is in the calling jQuery function. I am trying to send the parameter i
to the DeleteCurrentImage
function. Please guide me. Thank you. This code is written in MVC .cshtml file.
<div id="filesList">
@foreach (var item in imgArray)
{
var i = 0;
<div class="img101 floatleft" id="img101_' + i + '">
<img src="@item" />
<a href="#" id="DeleteCurrentImage" onclick="DeleteCurrentImage('+ i +');">Delete</a>
</div>
i += 1;
}
<div style="clear: both"></div>
</div>
答案 0 :(得分:1)
i
是C#代码中的变量,因此您需要将其输出到服务器端的HTML,而不是JS。您可以这样做:
<a href="#" onclick="DeleteCurrentImage(@i);">Delete</a>
请注意,当您创建无效的重复项时,我在此处删除了id
属性。
话虽这么说,使用不引人注目的事件处理程序代替on*
事件属性是一个更好的主意。然后,您可以简单地遍历DOM来查找与引发事件的元素相关的内容,而无需生成任何唯一的id
属性。用jQuery标记问题后,您可以像这样实现:
<div id="filesList">
@foreach (var item in imgArray)
{
<div class="img101 floatleft">
<img src="@item" />
<a href="#" class="DeleteCurrentImage">Delete</a>
</div>
}
<div style="clear: both"></div>
</div>
$('.DeleteCurrentImage').click(function() {
$(this).prev('img').remove();
});
请注意,这将删除同级img
元素。如果要删除整个包含div
的内容,请将.prev('img')
更改为.closest('div')
答案 1 :(得分:0)
您应该执行以下修复程序:
i
; #
id选择器开头)id
删除想要的元素增加我
<div id="filesList">
@{
var i = 0;
foreach (var item in imgArray)
{
<div class="img101 floatleft" id="img101_@(i)">
<img src="@item" />
<a href="#" onclick="DeleteCurrentImage('#img101_@(i)');">Delete</a>
</div>
i++;
}
}
<div style="clear: both"></div>
</div>
<script>
function DeleteCurrentImage(item) {
// Delete the element
$(item).remove();
}
</script>