jQuery的parents/closest方法无效

5

我有一个链接,可以将一些数据提交到控制器。它能有效地更新数据。但是我想改变父级div的CSS,但它并没有发生什么变化。我尝试了很多变化,但我一定是做错了什么。

以下是代码:

视图:

@foreach (var item in Model)
{
    <div class="added-property-excerpt">
        ...
        <div class="added-property-links">
        ...
        @if (!item.IsPropertyDisabled) { 
                @Html.ActionLink("Take off the Market" , "Disable", "Property", new { id = item.PropertyId }, new { id ="disable-link" })
            }
            else {
                @Html.ActionLink("Bring on the Market" , "Enable", "Property", new { id = item.PropertyId }, new { id ="enable-link" })
            }
        </div>
    </div>
}

JQuery

 <script>
     $(function () {
         $('a#disable-link').click(function (e) {
             $('.added-property-links').text('loading...');
             $.ajax({
                 url: this.href,
                 dataType: "text json",
                 type: "POST",
                 data: {},
                 success: function (data, textStatus) { }
             });
             $(this).closest('.added-property-excerpt').css("background", "red");
          // $(this).parent('.added-property-excerpt').css("background", "red");
             e.preventDefault();
         });
     });
 </script>

3
你能否发布一份导出的HTML文件样例? - VVV
1
你是否尝试过使用parents()而不是parent()? - Ja͢ck
您正在生成无效的标记。ID必须是唯一的。 - Ram
调试器/日志显示了什么?Ajax调用是否可能会抛出异常? - Rudolf Mühlbauer
“未定义” - 谢谢,我没有意识到这一点..目前我只有一个属性,所以这并不重要!我会让它们变得唯一。 - Tripping
@Ja͢ck 你太牛了!!! - maxisme
2个回答

5
你尝试过吗:
$(this).parents('.added-property-excerpt').css("background", "red");

parents 是复数形式。

它的作用是从父级元素到父级元素查找,直到找到你想要的类。


好的观点。我从未使用过closest,但现在我已经阅读了文档。谢谢。 - VVV

4

试试这个

$(function () {
    $('a#disable-link').click(function (e){
        var parentDiv=$(this).closest('.added-property-excerpt');
        $('.added-property-links').text('loading...');
        parentDiv.css("background", "red");
        $.ajax({...});
        e.preventDefault();
    });
});

查看工作示例非工作示例之间的差异。


3
非常感谢,程序现在运行完美了。但你能告诉我为什么之前的代码无法工作吗? - Tripping
2
@Tripping,我认为$('.added-property-links').text('loading...');这一行清除了dom中的link/<a> tag,导致$(this)在那一行之后无法引用它。 - The Alpha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接