在{strong>“来自Chrome扩展程序的跨域” </strong>”标题下的<a> tag

时间:2018-10-19 07:57:37

标签: jquery html asp.net-mvc

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>

2 个答案:

答案 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)

您应该执行以下修复程序:

  1. 在foreach之外初始化i
  2. 将所有带有调用id的函数的调用添加到cicle中(以# id选择器开头)
  3. 在函数中,通过传递的id删除想要的元素
  4. 增加我

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