.parent()。find('img')。eq(0)错误

时间:2018-06-06 06:54:32

标签: jquery html5

我想在'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()方法,但看不出是什么原因导致它无法在此页面上运行。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您不需要$(this).parent().find('img').eq(0);,因为您要获取的img位于所点击的元素中。您只需执行$(this).find('img').eq(0);

即可