首页 > 解决方案 > 使用 Jquery 在 foreach MVC Razor 表中定位特定 td

问题描述

我有一个为用户显示不同内容的表格。每行的最后一个 td 包含一个 Html.ActionLink 和一个隐藏的 ajax 加载器。当按下选择按钮时,我希望只显示该行加载器 gif。按下 select 时,我可以很容易地显示每一个,但我正在努力将 td 隔离到单个 td 并只显示那个 ONE 加载器。这是表格代码:

<table class="table" id="tblCifSelection">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.ClientName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.PolicyNumber)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.PolicyTypeDescription)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.EffDate)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.ExpDate)
    </th>

    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(model => item.ClientName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PolicyNumber)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.PolicyTypeDescription)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EffDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.ExpDate)
        </td>

        <td>
            @Html.ActionLink("Select", "CompleteCIF", new { UniqPolicy = item.UniqPolicy }, new { onclick = "loadFunction();"}) |
            @* @Html.ActionLink("Delete", "Delete", new { id=item.UniqPolicy })*@
            <img id="cifLoader" class="ml-2 loader" src="~/Images/ajax-loader (3).gif" />

        </td>
    </tr>
}

这是我正在使用的脚本。

 <script>
   $(document).ready(function () {
       $('.loader').hide();
   })

   function loadFunction() {
       $(this).closest('.loader').show();

       /* These are tests I ran to see what would work and what wouldn't */
       //$('tr').closest('td').attr(' .loader').show();
       //$('.loader').show(); //this shows all loaders. Only one that works.
       $('#tblCifSelection').closest('tr').children('td:nth-child(6) img#cifLoader').show();
       $(this).closest('tr').children('td:nth-child(6)').show();
   }
</script>  

在此先感谢您的帮助。

标签: jqueryasp.net-mvc

解决方案


感谢以上两位的帮助。我能够制定出可行的解决方案。表数据是一样的,不过我改了一小块..

 <td>
   @Html.ActionLink("Select", "CompleteCIF", new { UniqPolicy = item.UniqPolicy }, new { @onclick = "loaderFunction(this);"}) |
   <img id="cifLoader" class="ml-2 loader" src="~/Images/ajax-loader (3).gif" />        
 </td>

   function loaderFunction(t) {
       $(t).closest('tr').find('td .loader').show();
       //$('.loader').show(); //this shows all loaders
   }

这完美地工作。仅在按下所选按钮的 tr 上显示加载程序。


推荐阅读