$this -不能找到正确的jQuery选择器

$this - can't find the correct jQuery selector

本文关键字:jQuery 选择器 this 不能      更新时间:2023-09-26

由于我的html结构过于复杂(wordpress评论系统),我很难找到在页面上显示一些div的选择器。

我没有把它们全部粘贴在这里,而是创建了一个更简化的布局版本,并创建了几个fiddle。

  1. 这是显示所有div的完整页面:
https://jsfiddle.net/e25zvfyg/

  • 这就是我想要的工作方式。基本上,回复框和相关的现有评论是隐藏的,直到"回复"被点击,然后隐藏的div向下滑动。我已经包括了我的"非工作"JS在这个小提琴。希望有人能告诉我哪里做错了?
  • https://jsfiddle.net/yf3oagx7/

     (function ($) {
    $('.single-f3ed-reply').hide();
    $('.f3ed-reply').hide();
    $('a.this-reply').click(function () {
        $('.single-f3ed-reply').hide();
        $(this).parents().next('.single-f3ed-reply').slideDown('fast');
        $(this).parents().next('.f3ed-reply').slideDown('fast');
        return false;
    });
    })(jQuery);
    

    .parents()返回所有所选元素之上的元素。您不希望这样,您只希望在包含div/wrapper的位置向上移动。

    .next()返回下一项(经过过滤),这在parents()

    的上下文中没有意义

    向上到最近的div (closest),然后再向下(find)到你想要的项目:

        $(this).closest(".stream-wrap").find('.single-f3ed-reply').slideDown('fast');
        $(this).closest(".stream-wrap").find('.f3ed-reply').slideDown('fast');
    
    https://jsfiddle.net/yf3oagx7/1/

    快速破解:https://jsfiddle.net/e25zvfyg/2/

    使用:

    $(this).closest('article').find('.single-f3ed-reply').slideDown('fast');
    $(this).closest('article').find('.f3ed-reply').slideDown('fast');
    

    你可以试试——

    (function ($) {
    $('.single-f3ed-reply').hide();
    $('.f3ed-reply').hide();
    $('a.this-reply').click(function () {
        $('.single-f3ed-reply').hide();
        $(this).parent().parent().parent().find('.single-f3ed-reply').slideDown('fast');
        $(this).parent().parent().parent().find('.f3ed-reply').slideDown('fast');
        return false;
    });
    })(jQuery);
    

    你也可以使用jquery的close()函数来实现。

    (function ($) {
    $('.single-f3ed-reply').hide();
    $('.f3ed-reply').hide();
    $('a.this-reply').click(function () {
        $('.single-f3ed-reply').hide();
        $(this).closest('.stream-wrap').find('.single-f3ed-reply').slideDown('fast');
        $(this).closest('.stream-wrap').find('.f3ed-reply').slideDown('fast');
        return false;
    });
    })(jQuery);