首页 > 解决方案 > .parent().find('img').eq(0) 错误

问题描述

我想在“a”标签内捕获一个“img”,但不幸的是无法实现。下面是我的html:

<table class="table table-bordered">
    <thead>
        <tr>
            <td>Category Name</td>
            <td>Status</td>
            <td>Display Rank</td>
        </tr>
    </thead>
    <tbody>            
        @foreach (var category in Model)
        {
            <tr>
                <td style="width: 200px">
                    <span style="cursor: pointer">@category.Name</span>
                </td>
                <td style="width: 200px">
                    <div id="@category.ID">
                        @if (category.Status == 1)
                        {
                            <img src="~/img/ok-icon.png" />
                            <a href="javascript:void(0)" class="make-passive"><img val="@category.ID"  src="~/img/Alarm-Error-icon.png" /></a>
                        }
                        else if (category.Status == 0)
                        {
                            <a href="javascript:void(0)" class="make-active">
                                <img val="@category.ID" src="~/img/Alarm-Tick-icon.png" />
                            </a>
                            <img src="~/img/Close-icon.png" />
                        }
                    </div>
                </td>
                <td style="width: 160px">
                    <a href="javascript:void(0)" class="take-up">
                        <img src="~/img/Arrows-Up-4-icon.png" />
                    </a><br />
                    <a href="javascript:void(0)" class="take-down">
                        <img src="~/img/Arrows-Down-4-icon.png" />
                    </a>
                </td>
            </tr>
        }
    </tbody>
</table>

而且,这是我的 JS 代码:

<script type="text/javascript">
$(document).on('click', 'a.make-passive', function () {
    var imgPassive = $(this).parent().find('img').eq(0);
    var imgNo = imgPassive.attr('val');
    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: "@Url.Action("DeactivateCategory", "Admin")/" + imgNo,
        success: function (data) {
            alert(data.Name + "has been successfully removed among active categories.");
            $('#' + imgNo).html("trial by sword");
        },
        error: function (data) {
            alert(data.Name + "cannot be removed among the other categories. An error occured.");
        }
    });
});

通过放置调试器,我意识到问题来自var imgPassive = $(this).parent().find('img').eq(0);

我在其他几个页面上成功使用.parent().find()了方法,但看不到是什么使它在此页面上不起作用。

提前致谢!

标签: jqueryhtml

解决方案


您不需要$(this).parent().find('img').eq(0);,因为img您想要获取的是 clicked 元素内。你可以简单地做$(this).find('img').eq(0);


推荐阅读